5

Possible Duplicate:
How to set AUTO-SCROLLING of JTextArea in Java GUI?

I'm creating an application in which the user types the text in a TextField from which the text is appended to a TextArea when an actionPerformed.
The TextArea is added on a JScrollPane. When the number of line out of declared column the user can scroll to see the text. But he need to scroll every-time when he enters some text to TextArea via TextField because the last line appended to the TextArea does not automatically scroll to last line.
Can anybody help me out there how to either automatically or when the actionPerformed, the TextArea will be scrolled to last?

Community
  • 1
  • 1
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117

2 Answers2

5

the magic resides in the DefaultCaret.updatePolicy:

DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

for details, see also Rob's blog entry

kleopatra
  • 51,061
  • 28
  • 99
  • 211
3

Try this:

jTextArea.selectAll();
int last = jTextArea.getSelectionEnd();
jTextArea.select(last, last);

Where jTextArea is a reference to your TextArea.

However, the previous example might be extremely slow if there is a lot of text, so I've provided another way to do this:

jTextArea.setCaretPosition(jTextArea.getDocument().getLength());

EDIT: After surfing around on the Internet for alternative solutions and reading this answer to a similar question, I realized that @kleopatra's solution is the more effective. However, it is entirely your prerogative to accept whatever answer you see fit (I see you've accepted mine).

@kleopatra I upvoted you to compensate. :)

Community
  • 1
  • 1
fireshadow52
  • 6,298
  • 2
  • 30
  • 46
  • Why not just `jTextArea.setCaretPosition(jTextArea.getText().length());` ? – DRCB Dec 22 '11 at 13:08
  • @DRCB, no you should not use getText().length(). This causes unnecessary work to rebuild the text string from the Document. Instead you can use getDocument().getLength(), which does the same but is more efficient. – camickr Dec 22 '11 at 15:55
  • @camickr Wow. Taught me something new. :) I'll change my answer. Btw, I made a reference to your answer on a similar question. – fireshadow52 Dec 22 '11 at 15:58