Java Reference
In-Depth Information
private class HandleControlButton implements ActionListener {
// Constructor
public HandleControlButton(int buttonID) {
this.buttonID = buttonID;
// Store the
button ID
}
// Handle button click
public void actionPerformed(ActionEvent e) {
switch(buttonID) {
case PICK_LUCKY_NUMBERS:
int[] numbers = getNumbers();
// Get maxCount
random numbers
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i].setValue(numbers[i]);
// Set the
button VALUES
}
break;
case COLOR:
Color color = new Color(
flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
for(int i = 0 ; i < NUMBER_COUNT ; ++i)
luckyNumbers[i].setBackground(color);
// Set the
button colors
break;
}
}
private int buttonID;
}
Directory "Lottery 1"
How It Works
The constructor stores its argument value in the buttonID field so each listener object has the ID for
the button available. The actionPerformed() method uses the button ID to select the appropriate code
to execute for a particular button. Each case in the switch statement corresponds to a different button.
You could extend this to enable the class to handle as many different buttons as you want by adding case
statements. Because of the way you have implemented the method, each button must have a unique ID
associated with it. Of course, this isn't the only way to do this, as you'll see in a moment.
For the PICK_LUCKY_NUMBERS button event, you just call the getNumbers() method to produce a set of
numbers and then call the setValue() method for each selection button and pass a number to it. You
implement the setValue() method when you define the Selection class in detail.
For the COLOR button event, you create a new color by exclusive ORing (that is, XOR) the RGB value of
flipColor with the current button color. Recall from the discussion of the ^ operator (in Chapter 2) that
you can use it to exchange two values, and that is what you are doing here. You defined flipColor as
the result of exclusive ORing the two colors, Color.YELLOW and Color.RED , together. Exclusive ORing
flipColor with either color produces the other color, so you flip from one color to the other automat-
Search WWH ::




Custom Search