Scroll down automatically JTextArea for show the last lines added

user2381256 picture user2381256 · May 18, 2013 · Viewed 20.5k times · Source

I have written a Java application that receives information from a server every 10 seconds. I am wanting to display this information on a form.

Currently I am using a JTextArea. However, once the JTextArea is filled up, I cannot see the new information that is added to this JTextArea. Do I need to add scroll bars to the JTextArea? Or is there a completely new different control for GUI forms that is recommended to display information that is added every x seconds?

Answer

Paul Vargas picture Paul Vargas · May 18, 2013

DefaultCaret tries to make itself visible which may lead to scrolling of a text component within JScrollPane. The default caret behavior can be changed by the DefaultCaret#setUpdatePolicy method.

Assumption that the name of your variable is textArea, you only need to modify the policy of caret:

DefaultCaret caret = (DefaultCaret) textArea.getCaret(); // ←
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);       // ←
...
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(textArea);

* Thanks, mKorbel