Search code examples
javaswingjtextareakeylistenercaret

Setting caret position where caret has not been in JTextArea


Is there anyway I can set the caret position in my JTextArea where the caret position has not been before? I would like to add text to my JTextArea using KeyListener on the KeyEvent.VK_ENTER, and then set the caret position one line underneath where I add the text to the JTextArea.

Cheers,

Taylor


Solution

  • using KeyListener on the KeyEvent.VK_ENTER

    Don't use a KeyListener. Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings for more information.

    set the caret position one line underneath where I add the text to the JTextArea.

    Make sure you append a "\n" to the text area when you add the text. Then you can just use:

    textArea.setCaretPosition( textArea.getDocument().getLength() );