Java Reference
In-Depth Information
To see how the delegation model works in practice, we will look at an example that
handles one of the most commonly used event generators: the mouse. The example will
show how to handle the basic mouse and mouse motion events. (Note that it is also possible
to handle mouse wheel events, but this is left to you as an exercise.)
Handling Mouse and Mouse Motion Events
To handle mouse and mouse motion events, you must implement the MouseListener and
the MouseMotionListener interfaces. The MouseListener interface defines five methods.
If a mouse button is clicked, mouseClicked( ) is invoked. When the mouse enters a com-
ponent, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked when a mouse button is
pressed and released, respectively. The general forms of these methods are shown here:
void mouseClicked(MouseEvent me )
void mouseEntered(MouseEvent me )
void mouseExited(MouseEvent me )
void mousePressed(MouseEvent me )
void mouseReleased(MouseEvent me )
The MouseMotionListener interface defines two methods. The mouseDragged( )
method is called multiple times as the mouse is dragged. The mouseMoved( ) method is
called multiple times as the mouse is moved. Their general forms are shown here:
void mouseDragged(MouseEvent me )
void mouseMoved(MouseEvent me )
The MouseEvent object passed in me describes the event. MouseEvent defines a num-
ber of methods that you can use to get information about what happened. Possibly the most
commonly used methods in MouseEvent are getX( ) and getY( ) . These return the X and
Y coordinates of the mouse (relative to the window) when the event occurred. Their forms
are shown here:
int getX( )
int getY( )
Search WWH ::




Custom Search