I\'m working on a Java application with Swing-based GUI. The application uses JTextPane
to output log messages as follows: 1) truncate existing text to keep tot
The reason for this is that you are running the for loop in the event dispatch thread (see Event Dispatch Thread). This is the thread in which all user interface interactions happens.
If you are running a long task, then you should run it in a different thread, so that the user interface keeps responsive. If you need to make a change on the user interface, like changing text in your JTextPane and setting the caret position out of a different thread than the event dispatch thread, you need to invoke either EventQueue.invokeLater()
or EventQueue.invokeAndWait()
(see EventQueue).
I think the triggered events from setting the caret position are queued in your case and can only be processed, when the loop is finished (cause both are processed in event dispatch thread). So you should try something like this:
@Override
public void actionPerformed(ActionEvent e)
{
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < iter; i++)
{
final String display = String.format("%10d\n", i);
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
append(display);
}
});
} catch (Exception e) {
e.printStackTrace();
}
} // end for i
}
}).start();
}
Might be even better if you call EventQueue.invokeAndWait
only after x iterations and cache the previous results, which needs to be displayed.