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

When using JDK1.4.2 (or earlier) the most common suggestion you will find in the forums is to use code like the following:

textArea.append(...);
textArea.setCaretPosition(textArea.getDocument().getLength());

However, I have just noticed that in JDK5 this issue has actually been resolved by an API change. You can now control this behaviour by setting a property on the DefaultCaret of the text area. Using this approach the code would be:

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

Note:

The above suggestion to set the caret update policy does not work.

Instead you may want to check out Smart Scrolling which gives the user the ability to determine when scrolling should be automatic or not.

A more detailed description of automatic scrolling in a text area can be found here: Text Area Scrolling

Leave a Comment