How to display lines one by one on a JTextPane
and make a related JProgressBar
?
I have this loop:
int k;
for (k=0; k<array_TXT.length; k++) {
if (array_TXT[k] != null) {
textPane.append( array_TXT[k] );
}
}
I'd like to append every line array_TXT[k]
(string) on the JTextPane
one by one after few seconds and it has to be synchronized to a JProgressBar
.
In this way every time k
has a different value it will print on the text pane and the progress bar will always be related to those prints.
I have read about Thread.sleep(x);
but I don't know where to put it in order to reach my aim.
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling
Thread.sleep(n)
implement a SwingTimer
for repeating tasks or aSwingWorker
for long running tasks. See Concurrency in Swing for more details.You'll want to use a
SwingWorker
. It will allow you to execute the updates in the background, off the Event Dispatching Thread.The SwingWorker has methods to allow you to
publish
andprocess
updates back to the Event Dispatching Thread.It also allows you to fire and monitor progress updates
SwingWorker Example
Swing Timer Example
As suggest by Andrew, the following is an example of using a
SwingTimer
. If you find it useful, please give Andrew credit for the idea