Search code examples
javaswingcursorjtextarea

How to change the default cursor position of a JTextArea?


In previous question I asked how to set cursor to the bottom of the JTextArea. The answer was textField.getDocument().getLength() Technically, I can use textField.getDocument().getLength() after every text insert, but this is not convenient.

However, this is not exactly what I meant. I need to change the JTextArea PROPERTY of cursor position. In my program _result is JTextArea. It gets texts from multiple classes and methods, so using textField.getDocument().getLength() everytime after _result.append("text") is not convenient and makes code error prone and not flexible

Is there any way I could do something like:

// this is just a pseudocode
_result.setDefaultCursorPosition(bottom);

and then whenever text goes there (NO MATTER from what class or method), the cursor is always at the bottom.


Solution

  • This would move the caret to the end position after each document change:

    _result.getDocument().addDocumentListener(new DocumentListener() {
            private void atEnd() { 
                _result.setCaretPosition(_result.getText().length()); 
            }
            public void insertUpdate(DocumentEvent evt) { atEnd(); }
            public void removeUpdate(DocumentEvent evt) { atEnd(); }
            public void changedUpdate(DocumentEvent evt) { atEnd(); }
        });
    

    It still allows the user to re-position the caret by clicking, or by other calls to setCaretPosition.