Text Area Scrolling
Posted by Rob Camick on October 22, 2008
A JTextArea, added to a scroll pane, is commonly used to display messages generated by an application as it is easy to add messages to the text area using the append(…) method. When using a text area in this manner there is usually also a requirement that the text area scroll as each new message is added. Sometimes the text area scrolls automatically and sometimes it doesn’t. Why is this?
Based on my observations, when using JDK1.4.2, I have noticed that two requirements must be met for automatic scrolling:
- the append(…) must be done on the Event Dispatch Thread
- the caret must currently be positioned at the end of the text area before the append(…) method is invoked
I have also noted that initializing a text area at creation time using any of the following approaches will cause the caret to be positioned at the start of the text area (not the end as might be expected), and therefore scrolling will not happen automatically:
- JTextArea textArea = new JTextArea(“Initial text”, …);
- textArea.setText(“Initial text”);
- textArea.read(someFile, null);
So, in general, automatic scrolling will only work on an initially empty text area when you use the append(…) method that is invoked from the Event Dispatch Thread.
So what can we do when the above conditions are not met?
When using JDK1.4.2 (or earlier) the most common suggestion you will find in the forums is to use code like the following:
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();
I like the second approach because you only need to add the code in one place in your program. Using the earlier approach you need to make sure you reset the caret position every time you invoke the append(…) method.
Note: I probably should have titled this entry “Text Component Scrolling” since the suggestions will also apply to JTextPane.
Update September 29, 2015
Just noticed that setting the update policy of the caret no longer appears to work. So the options would appear to be to use the setCaretPosition(…) method or to use Smart Scrolling.