Java Reference
In-Depth Information
add(bar);
add(btn);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (isRunning) {
// How to cancel here?
} else {
isRunning = true;
btn.setText("Stop Calculation");
long total = 1000000000;
for (long i = 0; i < total; i++) {
int perc = (int)
(i * (bar.getMaximum() - bar.getMinimum())
/ total);
bar.setValue(perc);
}
}
isRunning = false;
btn.setText("Start Calculation");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() { new ProgressTrackingFrame(); }
});
}
Try running the program and starting the calculation. Unless you have a very fast machine, the loop
will take some time to finish. Notice how the rest of the UI becomes frozen during the execution of
the action listener. Try resizing the window. You'll note that this will lead to a garbled result that's
typical for programs that do not redraw their UI anymore, as shown in Figure 11-21.
figure 11-21  
In some cases, Windows will notice that your program is not responding and might attempt to close
it. Just wait a few more seconds, however, and you'll see that the program suddenly pops into life
again and the event loop catches up to handle the other events. This is because the event listener
includes heavy‐duty code that is run inside the EDT.
Of course, you would like a way to improve things, and if possible, you'd also like to implement a
way to cancel a running calculation.
Search WWH ::




Custom Search