Java Reference
In-Depth Information
public BarThread (JProgressBar bar) {
progressBar = bar;
}
public void run() {
int minimum = progressBar.getMinimum();
int maximum = progressBar.getMaximum();
for (int i=minimum; i<maximum; i++) {
try {
// Our job for each step is to just sleep
Thread.sleep(DELAY);
} catch (InterruptedException ignoredException) {
} catch (InvocationTargetException ignoredException) {
// The EventQueue.invokeAndWait() call
// we'll add will throw this
}
}
}
}
4.
For each step, have the thread update the progress bar in the event thread. Create the
Runnable
class just once outside the
for
loop. It isn't necessary to create one for each step.
Runnable runner = new Runnable() {
public void run() {
int value = progressBar.getValue();
progressBar.setValue(value+1);
}
};
Within the loop, tell the runner to update the progress bar. This update must be done in
the event thread using the special
EventQueue
method
invokeLater()
or
invokeAndWait()
,
because you're updating a property of the
JProgressBar
.
EventQueue.invokeAndWait (runner);
The complete working example is shown in Listing 12-5.
Listing 12-5.
JProgressBar Sample
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
public class ProgressBarStep {
static class BarThread extends Thread {
private static int DELAY = 500;
JProgressBar progressBar;