Java Reference
In-Depth Information
The Event Objects (continued)
The java.awt.Component class, which is the parent of all components, contains an
addMouseListener() method. This implies that all components are the source of
MouseEvent, which is true because all components can interact with the mouse in some
manner. The following code from the HighlightDemo program (see the Web site for this
book for a complete listing) creates six JButton components and registers a HighlightCom-
ponent listener with each component, as well as the JFrame's content pane. What do you
think happens when this program executes and the user moves the mouse over the vari-
ous components in the window?
buttons = new JButton[6];
HighlightComponent listener =new HighlightComponent();
contentPane.addMouseListener(listener);
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(“Click “ + (i + 1));
contentPane.add(buttons[i]);buttons[i].addMouseListener(listener);
}
Figure 13.2 shows the output of the HighlightDemo program when the mouse is hov-
ering over the button labeled Click 2.
Figure 13.2
The Click 2 button is highlighted when the mouse is over it.
When the mouse leaves the Click 2 button, the button changes back to its regular color
and the background of the window becomes white. When the mouse moves back over a
button, the window goes back to its regular color and the corresponding mouse becomes
white. Note that the HighlightComponent listener class was simplified by the listener's
being able to get the source of the event invoking getSource(), which can be invoked on
any event object.
As I discuss the various components in this chapter, I will discuss many of the event
classes and how to use them to obtain useful information about the event that is being lis-
tened for.
Search WWH ::




Custom Search