Java Reference
In-Depth Information
Again, luckily, Swing already provides a mechanism to do this in a fairly simple manner, by
means of the SwingWorker class. This class allows you to construct objects that represent some
kind of background task. Here's how you can implement it. First of all, define a new class field
like so:
private SwingWorker<Boolean, Integer> backgroundTask = null;
You can remove the isRunning field, as you'll no longer need it. Next, create a method to construct
a background task for you:
public SwingWorker<Boolean, Integer> makeBackgroundTask(final long total) {
}
This method will construct a new SwingWorker anonymous inner class. You will need to provide
two type parameters to this class. The first one represents the type of the final result value (you use a
Boolean here). The second one represents the type of the intermediate result values ( Integer is used
here as these will be sent out to update the progress bar):
public SwingWorker<Boolean, Integer> makeBackgroundTask(final long total) {
SwingWorker<Boolean, Integer> task = new SwingWorker<Boolean, Integer>(){
@Override
protected Boolean doInBackground() throws Exception {
return true;
}
};
return task;
}
The doInBackground method needs to be implemented and has to have your indicated final result
type as a return type (Boolean). This method contains the work that will be performed in the back-
ground, so fill it up with your loop:
public SwingWorker<Boolean, Integer> makeBackgroundTask(final long total) {
SwingWorker<Boolean, Integer> task = new SwingWorker<Boolean, Integer>(){
@Override
protected Boolean doInBackground() throws Exception {
btn.setText("Stop Calculation");
for (long i = 0; i < total; i++) {
int perc = (int)
(i * (bar.getMaximum() - bar.getMinimum())
/ total);
}
return true;
}
};
return task;
}
Although you could still update the progress bar value inside this method, SwingWorker also pro-
vides a way to work with intermediate values in a better manner, by using its publish method. This
method will queue intermediate results that can then be processed by a process method. You don't
Search WWH ::




Custom Search