Java Reference
In-Depth Information
Try It Out - Setting up the Control Buttons
The listeners for each of the control buttons will be of the same class type, so the listener object will
need some way to determine which button originated a particular event. One way to do this is to use
constants as IDs to identify the control buttons, and pass the appropriate ID to the class constructor for
the listener object.
We could define the constants
PICK
_
LUCKY
_
NUMBERS
and
COLOR
as fields in the
Lottery
class for
this purpose. The
COLOR
control button will also reference a couple of
Color
variables,
startColor
and
flipColor.
You can add the following statements to the
Lottery
class after the definition of the
luckyNumbers
array:
// An array of custom buttons for the selected numbers
private Selection[] luckyNumbers = new Selection[numberCount];
final public static int PICK
_
LUCKY
_
NUMBERS = 1; // Select button ID
final public static int COLOR = 2; // Color button ID
// swap colors
Color flipColor = new Color(Color.yellow.getRGB()^Color.red.getRGB());
Color startColor = new Color(Color.yellow.getRGB()); // start color
The code to add the other panel and the control buttons is as follows:
// Initialize the applet
public void init() {
// Setting up the selections buttons as previously...
// Add the pane containing control buttons
JPanel controlPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 10));
// Add the two control buttons
JButton button; // A button variable
Dimension buttonSize = new Dimension(100,20); // Button size
controlPane.add(button = new JButton("Lucky Numbers!"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new HandleControlButton(PICK
_
LUCKY
_
NUMBERS));
button.setPreferredSize(buttonSize);
controlPane.add(button = new JButton("Color"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new HandleControlButton(COLOR));
button.setPreferredSize(buttonSize);
content.add(controlPane);
}