Java Reference
In-Depth Information
need to manually call the latter, as SwingWorker will determine when (based on time and results
gathered) it is a good time to call this method:
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);
publish(perc);
}
return true;
}
@Override
protected void process(List<Integer> percs) {
for (int perc : percs)
if (bar.getValue() < perc)
bar.setValue(perc);
}
};
return task;
}
You can also use the isCancelled method to figure out whether your background task was can-
celled from the outside. It is a good idea to check the result of this method as often as possible so
a cancellation request can be dealt with as soon as possible, for instance in the deepest level of a
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++) {
if (isCancelled()) {
bar.setValue(0);
return false;
}
int perc = (int)
(i * (bar.getMaximum() - bar.getMinimum())
/ total);
publish(perc);
}
return true;
}
@Override
protected void process(List<Integer> percs) {
for (int perc : percs)
if (bar.getValue() < perc)
bar.setValue(perc);
}
Search WWH ::




Custom Search