简体   繁体   中英

How to enter text at the beginning of JTextField

Is there a way to add functionality that would enable a user to type into a JTextField but the cursor stays at the beginning of the input, thus making the text backward?

Example:

User types '5'

5 is displayed

User types '9'

95 is displayed

If you need this to happen only with numbers, I suggest you to use a JSpinner component instead of a JTextField . But with textField you can achieve it like this:

    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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM