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

Viewed 102715

I have embedded a JTextArea on a JScrollPane and am using that JTextArea for output.

I want that whenever the ouput goes beyond the size of the JTextArea, the JTextArea scrolls automatically so that user don't have to do manual scroll down to see the recent output.

How can I do that?

I have already set the autoscroll property of both JTextArea and JScrollPane to true.

8 Answers

I tried most suggestions but ran into problems when the content of the JTextArea becomes large (several MB). Finally the following showed best performance:

myTextArea.append( someText );
myTextArea.getCaret().setDot( Integer.MAX_VALUE );

Of course, any selection the user had made gets lost. Hence, its only usable for a "display-only" usage of the text area.

Still, in my installation, if the content of the JTextArea exceeds some 9MB, it gets kind of unusable (very sluggish to almost frozen GUI).

A similar phenomenon occurs when the text contains characters that are represented by two chars (two 16-bit units) in the UTF-16 encoding (so-called surrogate pairs, like this: ). I have a solution for filtering, but maybe a different topic.

Best and easiest way, Try this :

  import javax.swing.text.DefaultCaret;
  DefaultCaret caret = (DefaultCaret) textArea.getCaret();
  caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

Try this:

JTextArea jTextArea = new JTextArea();
JScrollPane jScrollPane = new JScrollPane();
jScrollPane.setViewport(jTextArea);
Related