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

Était-ce utile?

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

Autres conseils

  • 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(...)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top