Java Reference
In-Depth Information
116 southJPanel.add(cancelJButton);
117 progressJProgressBar.setStringPainted( true );
118 southJPanel.add(progressJProgressBar);
119 southJPanel.add(statusJLabel);
120
121 add(northJPanel, BorderLayout.NORTH );
122 add(southJPanel, BorderLayout.SOUTH );
123 setSize( 350 , 300 );
124 setVisible( true );
125 } // end constructor
126
127 // main method begins program execution
128 public static void main(String[] args)
129 {
130 FindPrimes application = new FindPrimes();
131 application.setDefaultCloseOperation( EXIT_ON_CLOSE );
132 } // end main
133 } // end class FindPrimes
Fig. 23.27 | Using a SwingWorker to display prime numbers and update a JProgressBar
while the prime numbers are being calculated. (Part 4 of 4.)
Lines 42-94 register the event handler for the getPrimesJButton . When the user
clicks this JButton , lines 47-49 reset the JProgressBar and clear the displayPrimes-
JTextArea and the statusJLabel . Lines 53-63 parse the value in the JTextField and dis-
play an error message if the value is not an integer. Lines 66-68 construct a new
PrimeCalculator object, passing as arguments the integer the user entered, the display-
PrimesJTextArea for displaying the primes, the statusJLabel and the two JButton s.
Lines 71-85 register a PropertyChangeListener for the PrimeCalculator object.
PropertyChangeListener is an interface from package java.beans that defines a single
method, propertyChange . Every time method setProgress is invoked on a PrimeCalcu-
lator , the PrimeCalculator generates a PropertyChangeEvent to indicate that the prog-
ress property has changed. Method propertyChange listens for these events. Line 78 tests
whether a given PropertyChangeEvent indicates a change to the progress property. If so,
line 80 gets the new value of the property and line 81 updates the JProgressBar with the
new progress property value.
The Get Primes JButton is disabled (line 88) so only one calculation that updates the
GUI can execute at a time, and the Cancel JButton is enabled (line 89) to allow the user
 
Search WWH ::




Custom Search