如何在JTextField的开头输入文本

问题描述 投票:0回答:1

是否有添加功能的方法,使用户可以键入JTextField但光标停留在输入的开头,从而使文本向后移动?

示例:

用户类型'5'

显示5

用户类型为'9'

显示95

java jtextfield
1个回答
0
投票

[如果您只需要数字就可以做到这一点,建议您使用JSpinner组件而不是JTextField。但是,使用textField可以这样实现:

    JTextField field = new JTextField();
    AbstractDocument document = (AbstractDocument) field.getDocument();
    document.setDocumentFilter(new DocumentFilter() {
        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
                throws BadLocationException {
            offset = 0;//Insert string at offset 0
            super.insertString(fb, offset, string, attr);
        }
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {
            offset = 0; //Insert string at offset 0
            super.replace(fb, offset, length, text, attrs);
        }
    });
© www.soinside.com 2019 - 2024. All rights reserved.