Java Reference
In-Depth Information
Most tasks requiring a ProgressMonitor will be implemented using separate threads to
avoid blocking the responsiveness of the main program.
Listing 9-5 shows a program that creates a ProgressMonitor and allows you to either manually
or automatically increase its progress property (see the following section for a description of
this property). These tasks are handled by on-screen buttons (see Figure 9-16). Selecting the
Start button creates the ProgressMonitor . Selecting the Manual Increase button causes the
progress to increase by 5. Selecting the Automatic Increase button causes the progress to
increase by 3 every 250 milliseconds (1/4 second). Pressing the Cancel button in the pop-up
window during the automatic increase demonstrates what should happen when the operation
is canceled; the timer stops sending updates.
Figure 9-16. Main ProgressMonitor sample frame
Note The pop-up window won't appear until some progress is shown.
The ProgressMonitorHandler inner class at the start of Listing 9-5 is necessary to ensure
that the ProgressMonitor is accessed only from the event thread. Otherwise, the access wouldn't
be thread-safe in some random thread.
Listing 9-5. Sample ProgressMonitor Usage
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SampleProgress {
static ProgressMonitor monitor;
static int progress;
static Timer timer;
static class ProgressMonitorHandler implements ActionListener {
// Called by Timer
public void actionPerformed(ActionEvent actionEvent) {
if (monitor == null)
return;
 
Search WWH ::




Custom Search