Question

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

Was it helpful?

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

OTHER TIPS

  • I strongly urge you to not use a KeyListener as the use of low-level listeners is discouraged and can make your code harder to upgrade and modify.
  • What is your ultimate goal as there may be a better way.
  • To add a new line, simply do that: add a new line to the JTextArea via textArea.append("\n");
  • Then advance the cursor to the end of the JTextArea via setCaretPosition(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top