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?