Java Reference
In-Depth Information
A Swing worker only needs one method, doInBackground() , which performs the task in
the background. The method must use the protected level of access control and return a
value produced by the work. DiceWorker creates a 16-element integer array that contains
dice-roll results.
Another class can use this worker in three steps:
1. Call the worker's DiceWorker( int ) constructor with the number of rolls as the
argument.
2. Call the worker's addPropertyChangeListener( Object ) method to add a listener
that will be notified when the task is complete.
3. Call the worker's execute() method to begin the work.
The execute() method causes the worker's doInBackground() method to be called.
A property change listener is an event listener borrowed from java.beans , the JavaBeans
package that establishes ways in which components on a user interface can interact with
each other.
In this case, a Swing worker wants to announce that its work has been finished, which
could take place long after the worker began its work. Listeners are the best way to han-
dle notifications of this kind because they free a graphical user interface to handle other
things.
The property change listener interface has one method:
public void propertyChange(PropertyChangeEvent event) {
// ...
}
The DiceRoller class shown in Listing 14.3 presents a graphical user interface that can
display dice-roll results and begin a set of rolls.
LISTING 14.3
The Full Text of DiceRoller.java
1: import java.awt.*;
2: import java.awt.event.*;
3: import java.beans.*;
4: import javax.swing.*;
5:
6: public class DiceRoller extends JFrame implements ActionListener,
7: PropertyChangeListener {
8:
9: // the table for dice-roll results
Search WWH ::




Custom Search