Home » Java » java – How to enter text at the beginning of JTextField-Exceptionshub

java – How to enter text at the beginning of JTextField-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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

How to&Answers:

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