Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up


Writing a Mouse Listener

Mouse events tell you when the user uses the mouse (or similar input device) to interact with a component. Mouse events occur when the cursor enters or exits a component's on-screen area and when the user presses or releases the mouse button. Because tracking the cursor's motion involves significantly more system overhead than tracking other mouse events, mouse motion events are separated into a separate listener type (see Writing a Mouse Motion Listener).

Mouse Event Methods

The MouseListener(in the API reference documentation) interface and its corresponding adapter class, MouseAdapter(in the API reference documentation), contain three methods:
void mouseClicked(MouseEvent)
Notifies the listener ...
void mouseEntered(MouseEvent)
Notifies the listener ...
void mouseExited(MouseEvent)
Notifies the listener ...
void mousePressed(MouseEvent)
Notifies the listener ...
void mouseReleased(MouseEvent)
Notifies the listener ...

Examples of Handling Mouse Events

The following applet demonstrates mouse events. [describe applet]

Since you can't run the applet, here's a picture of it:


Try this:
  1. Do something...

You can find the applet's code in MouseDemo.java. Here is the applet's mouse event handling code:

[code goes here]

You can find more examples of mouse listeners in the following sections: [LIST GOES HERE]

The MouseEvent Class

Each mouse event method has a single parameter: a MouseEvent(in the API reference documentation) object. The MouseEvent class defines the following useful methods:

int getClickCount()
Returns the number of quick, consecutive clicks the user has made (including this event)[CHECK].

int getX()
int getY()
Point getPoint()
Return the (x,y) position at which the event occurred, relative to the component over which the event occurred.

The MouseEvent class extends InputEvent(in the API reference documentation), which extends ComponentEvent(in the API reference documentation). ComponentEvent provides the handy getComponent method. InputEvent provides the following useful methods:

int getWhen()
Returns the timestamp of when this event occurred. The higher the timestamp, the more recently the event occurred. [CHECK!]

boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
Convenient methods giving you the state of the modifier keys when the event was generated.

int getModifiers()
Returns a flag indicating the state of all the modifier keys when the event was generated.


Previous | Next | Trail Map | To 1.1 -- And Beyond! | GUI Changes: The AWT Grows Up