Java Reference
In-Depth Information
colorButton.setPreferredSize(buttonSize);
colorButton.setBorder(BorderFactory.createRaisedBevelBorder());
pickButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[] numbers = getNumbers();
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i].setValue(numbers[i]);
}
}
});
colorButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(
flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i].setBackground(color);
}
}
});
controlPane.add(pickButton);
controlPane.add(colorButton);
content.add(controlPane);
Now the two listeners are defined by anonymous classes, and the implementation of the actionPer-
formed() method in each just takes care of the particular button for which it is listening. This is a very
common technique when the action to be performed in response to an event is simple, as it is in this case.
Handling Low-Level and Semantic Events
I said earlier in this chapter that a component generates both low-level and semantic events, and you could
handle both if you want. I can demonstrate this quite easily with a small extension to the Lottery applet.
Suppose you want to change the cursor to a hand cursor when it is over one of the selection buttons. This
would be a good cue that you can select these buttons individually. You can do this by adding a mouse listen-
er for each button.
TRY IT OUT: A Mouse Listener for the Selection Buttons
There are many ways in which you could define the listener class. Here you define it as a separate class
called MouseHandler :
Search WWH ::




Custom Search