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.
JPanel panel = new JPanel(); JScrollPane scrollPane = new JScrollPane( panel ); When you add buttons to the panel at run time the code should be: panel. add( button ); panel.
You can create a ScrollController and pass it to the controller parameter of your scrolling widget. Then you can use the animateTo method to animate to an offset.
public interface Scrollable. An interface that provides information to a scrolling container like JScrollPane. A complex component that's likely to be used as a viewing a JScrollPane viewport (or other scrolling container) should implement this interface.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With