Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reach at the end of the TextArea [duplicate]

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?

like image 998
Mohammad Faisal Avatar asked Dec 22 '11 12:12

Mohammad Faisal


2 Answers

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

like image 106
kleopatra Avatar answered Oct 04 '22 03:10

kleopatra


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. :)

like image 34
fireshadow52 Avatar answered Oct 04 '22 03:10

fireshadow52