Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 254
Yatendra Avatar asked Oct 26 '09 20:10

Yatendra


People also ask

How do I add a scroll pane in Java?

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.

How do I scroll automatically in flutter?

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.

What is scrollable in Java?

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.


1 Answers

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

like image 71
camickr Avatar answered Oct 18 '22 01:10

camickr