Java Reference
In-Depth Information
};
return task;
}
Finally, you can also override the done method to update your UI:
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);
}
@Override
public void done() {
btn.setText("Start Calculation");
backgroundTask = null;
}
};
return task;
}
Next, the only thing left to do is to change your original action listener so it now sets up and exe-
cutes your background task, using the execute method. Use the cancel method to send a cancella-
tion request in case the user wants to cancel the calculation. The final result looks like this:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ProgressTrackingFrame extends JFrame implements ActionListener {
private final JProgressBar bar = new JProgressBar(0, 100);
private final JButton btn = new JButton("Start Calculation");
Search WWH ::




Custom Search