Java Reference
In-Depth Information
for(int i = 0; i < numberCount; 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 < numberCount; 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
actionPerformed() 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.
Handling Low-level and Semantic Events
We said earlier in this chapter that a component generates both low-level and semantic events, and you
could handle both if you want. We can demonstrate this quite easily with a small extension to the
Lottery applet. Suppose we 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. We can do
this by adding a mouse listener 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. We'll define it as a separate class,
called MouseHandler :
// Mouse event handler for a selection button
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
class MouseHandler extends MouseAdapter {
Cursor handCursor = new Cursor(Cursor.HAND _ CURSOR);
Cursor defaultCursor = new Cursor(Cursor.DEFAULT _ CURSOR);
// Handle mouse entering the selection button
public void mouseEntered(MouseEvent e) {
e.getComponent().setCursor(handCursor); // Switch to hand cursor
}
Search WWH ::




Custom Search