Java Reference
In-Depth Information
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
// Get source object reference
if(source == pickButton) {
// Is it the pick button?
int[] numbers = getNumbers();
// Get maxCount random numbers
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i].setValue(numbers[i]);
// Set the button values
}
} else if(source == colorButton) {
// Is it the color button?
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
}
}
}
}
You no longer need to define a constructor, as the default is sufficient. The actionPerformed() method
now decides what to do by comparing the reference returned by the getSource() method for the event ob-
ject with the two button references in the JButton fields of the Lottery class. With the previous version
of the listener class, you stored the ID as a data member, so a separate listener object was needed for each
button. In this case there are no data members in the listener class, so you can use one listener object for
both buttons. This is clearly a better way of handling the button events that the previous approach.
The code to add these buttons in the createGUI() method would then be the following:
// Add the two control buttons
Dimension buttonSize = new Dimension(100,20);
pickButton.setPreferredSize(buttonSize);
pickButton.setBorder(BorderFactory.createRaisedBevelBorder());
colorButton.setPreferredSize(buttonSize);
colorButton.setBorder(BorderFactory.createRaisedBevelBorder());
HandleControlButton controlHandler = new HandleControlButton();
pickButton.addActionListener(controlHandler);
colorButton.addActionListener(controlHandler);
controlPane.add(pickButton);
controlPane.add(colorButton);
content.add(controlPane);
The only fundamental difference here is that you use one listener object for both buttons.
There is another possible way to implement listeners for these buttons. You could define a separate class
for each listener — this would not be unreasonable, as the actions to be performed in response to the semant-
ic events for each button are quite different. You could use anonymous classes in this case — as I discussed
in Chapter 6. You could do this by adding the listeners for the button objects in the createGUI() method
like this:
// Add the two control buttons
Dimension buttonSize = new Dimension(100,20);
pickButton.setPreferredSize(buttonSize);
pickButton.setBorder(BorderFactory.createRaisedBevelBorder());
Search WWH ::




Custom Search