Java Reference
In-Depth Information
// Handle mouse exiting the selection button
public void mouseExited(MouseEvent e) {
e.getComponent().setCursor(defaultCursor); // Change to default cursor
}
}
All we need to do to expedite this is to add a mouse listener for each of the six selection buttons. We
only need one listener object and after creating this we only need to change the loop in the init()
method for the applet to add the listener:
int[] choices = getNumbers(); // Get initial set of numbers
MouseHandler mouseHandler = new MouseHandler(); // Create the listener
for(int i = 0 ; i<numberCount ; i++) {
luckyNumbers[i] = new Selection(choices[i]);
luckyNumbers[i].addMouseListener(mouseHandler);
buttonPane.add(luckyNumbers[i]);
}
How It Works
The mouseEntered() method will be called when the mouse enters the area of the component with
which the listener is registered, and we can then change the cursor for the component to a hand cursor.
When the cursor is moved out of the area occupied by the component, the mouseExited() method is
called, and we restore the default cursor.
There are just two extra statements in init() that create the listener object and then add it for each
selection button within the loop. If you recompile the applet and run it again, a hand cursor should
appear whenever the mouse is over the selection buttons. Of course, you are not limited to just
changing the cursor in the event handle. You could highlight the button by changing its color for
instance. You could apply the same technique for any kind of component where the mouse is the source
of actions for it.
Semantic Event Listeners in an Application
An obvious candidate for implementing semantic event listeners is in the Sketcher program, to support
the operation of the menu bar in the class SketchFrame . When we click on an item in one of the pull-
down menus, a semantic event will be generated that we can listen for and then use to determine the
appropriate program action.
Listening to Menu Items
We will start with the Elements menu. This is concerned with identifying the type of graphic element to
be drawn next, and the color in which it will be drawn. We won't be drawing them for a while, but we
can put in the infrastructure to set the type and color for an element without worrying about how it will
actually be created and drawn.
Search WWH ::




Custom Search