Java Reference
In-Depth Information
The next example will use these methods to display the current location of the mouse.
A Simple Mouse Event Applet
The following applet demonstrates handling the basic mouse events. It displays the current
coordinates of the mouse in the applet's status window. Each time a button is pressed, the
word "Down" is displayed at the location of the mouse pointer. Each time the button is
released, the word "Up" is shown. If a button is clicked, the message "Mouse clicked." is
displayed in the upper-left corner of the applet display area.
As the mouse enters or exits the applet window, a message is displayed in the upper-
left corner of the applet display area. When dragging the mouse, a * is shown, which
tracks with the mouse pointer as it is dragged. Notice that the two variables,
mouseX
and
mouseY
, store the location of the mouse when a mouse pressed, released, or dragged event
occurs. These coordinates are then used by
paint( )
to display output at the point of these
occurrences.
Ask the Expert
Q
:
You state that the
getX( )
and
getY( )
methods defined by
MouseEvent
return the
window-relative coordinates of the mouse. Are there methods that return its
screen-relative (that is, absolute) location?
A
:
Yes.
MouseEvent
defines methods that obtain the X and Y coordinates of the mouse
relative to the screen. They are shown here:
int getXOnScreen( )
int getYOnScreen( )
You might find it interesting to experiment with these methods by substituting them for
getX( )
and
getY( )
in the
MouseEvents
applet shown next.