0

I'm trying to log infomation onto the JTextArea as process occurs in the background. When the users click the button, i want the messages can show up int the JTextArea immediately and when the JTextArea is full,the JScrollPane can scroll down automatically.

I have tryed many method in the stackoverflow.

The JTextArea can refresh immediately.But the JScrollPane still can not scroll down automatically.

At last, I found a method.I put the code in the thread like below.

public class MyRunnable implements Runnable
{

    @Override
    public void run() 
    {
       //code......
    }
}

public class nodeListBtnListener implements ActionListener
{
    @Override
    public void actionPerformed(ActionEvent e) 
    {
        Runnable threadJob = new MyRunnable();
        Thread myThread = new Thread(threadJob);
        myThread.start();
    }   
}

......
text = new JTextArea(20,18);
//important
DefaultCaret caret = (DefaultCaret)text.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
......

The JScrollPane can scroll down automatically.

These codes are not needed.

text.setSelectionStart(text.getText().length());//not needed.

text.update(text.getGraphics());//not needed

text.setCaretPosition(text.getDocument().getLength());//not needed

My question is why the JScrollPane can scroll down, when I put it in the thread?

Saxon
  • 33
  • 8
  • 1
    [This](http://stackoverflow.com/questions/13437865/java-scroll-to-specific-text-inside-jtextarea/13438455#13438455) is an example of scroll to a specific point in the `JTextArea`. Typically when I want to scroll to the bottom, I just set the caret position to the length of the string – MadProgrammer Jan 14 '17 at 08:58
  • 1
    Probably a little more complicated, but [this example](http://stackoverflow.com/questions/29224709/jtextarea-scroll-to-bottom-only-if-text-is-appended/29224842#29224842) will show the use of `setCaretPosition`. If none of that is working, then you will need to provide a runnable example of what you're doing that isn't – MadProgrammer Jan 14 '17 at 09:00

0 Answers0