Java Reference
In-Depth Information
flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
for(int i = 0; i < numberCount; i++)
luckyNumbers[i].setBackground(color); // Set the button colors
}
}
}
We no longer need to define a constructor, as the default will do. The actionPerformed() method
now decides what to do by comparing the reference returned by the getSource() method for the
event object with the two button references. With the previous version of the listener class, we 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 we can use one listener object for both buttons.
The code to add these buttons in the init() method would then be:
// 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 we use one listener object for both buttons.
There is another possible way to implement listeners for these buttons. We could define a separate class
for each listener - this would not be unreasonable as the actions to be performed in response to the
semantic events for each button are quite different. We could use anonymous classes in this case - as we
discussed back in Chapter 6. We could do this by adding the listeners for the button objects in the
init() method like this:
// 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());
pickButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[] numbers = getNumbers();
Search WWH ::




Custom Search