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.


Solution 1:

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

Solution 2:

    JScrollBar vbar = scrollPane.getVerticalScrollBar();

    for (int i = 0; i < 20; i++) {

        myJTxt.append("This is text " + i + "\n");
        vbar.setValue(vbar.getMaximum());
        vbar.paint(vbar.getGraphics());
        myJTxt.scrollRectToVisible(myJTxt.getVisibleRect());
        myJTxt.paint(myJTxt.getGraphics());
        try {
            Thread.sleep(250);
        } catch (InterruptedException ex) {
            Logger.getLogger(ScrollTextView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Solution 3:

When you click anywhere over JTextArea, auto-scrolling have possible to be stopped. Because the position of caret once changed, view point changed too. In this time you should set caret position when you append or add some text. On my way, I made method including set caret position, and then use it when anything to be added or appended.

Solution 4:

    JTextArea jTextArea = new JTextArea();
    DefaultCaret caret = (DefaultCaret)jTextArea.getCaret();
    caret.setUpdatePolicy(DefaultCaret.OUT_BOTTOM);