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?
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
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With