Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners

How to Write 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 How to Write a Mouse Motion Listener).

[PENDING: mention swing's MouseInputAdapter dodad]

Mouse Event Methods

The MouseListener(in the API reference documentation) interface and its corresponding adapter class, MouseAdapter(in the API reference documentation), contain these methods:
void mouseClicked(MouseEvent)
Called just after the user clicks the listened-to component.
void mouseEntered(MouseEvent)
Called just after the cursor enters the bounds of the listened-to component.
void mouseExited(MouseEvent)
Called just after the cursor exits the bounds of the listened-to component.
void mousePressed(MouseEvent)
Called just after the user presses a mouse button while the cursor is over the listened-to component.
void mouseReleased(MouseEvent)
Called just after the user releases a mouse button after a mouse press over the listened-to component.

One complication affects mouse-entered, mouse-exited, and mouse-released events. When the user drags (presses and holds the mouse button and then moves the mouse), then the component that the cursor was over when the drag started is the one that receives all subsequent mouse and mouse-motion events up to and including the mouse button release. That means that no other component will receive a single mouse event -- not even a mouse-released event -- while the drag is occurring.

Examples of Handling Mouse Events

The following applet contains a mouse listener. At the top of the applet is a blank area (implemented, strangely enough, by a class named BlankArea). The mouse listener listens for events both on the BlankArea and on its container, which is an instance of MouseEventDemo. Each time a mouse event occurs, a descriptive message is displayed under the blank area. By moving the cursor on top of the blank area and occasionally pressing mouse buttons, you can generate mouse events.

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.


Try this:
  1. Move the cursor into the yellow rectangle at the top of the applet.
    You'll see one or more mouse-entered events.
  2. Press and hold the mouse button.
    You'll see a mouse-pressed event. You might see some extra mouse events, such as mouse-exited and then mouse-entered.
  3. Release the mouse button.
    You'll see a mouse-released event. If you didn't move the mouse, a mouse-clicked event will follow.
  4. Press and hold the mouse button, and then drag the mouse so that the cursor ends up outside the applet's area. Release the mouse button.
    You'll see a mouse-pressed event, followed by a mouse-exited event, followed by a mouse-released event. You are not notified of the cursor's motion. To get mouse-motion events, you need to implement a mouse-motion listener.

You can find the applet's code in MouseEventDemo.java and BlankArea.java. Here is the applet's mouse event handling code:
public class MouseEventDemo ... implements MouseListener {
	...//where initialization occurs:
        //Register for mouse events on blankArea and applet (panel).
        blankArea.addMouseListener(this);
        addMouseListener(this);
    ...

    public void mousePressed(MouseEvent e) {
       saySomething("Mouse pressed; # of clicks: "
                    + e.getClickCount(), e);
    }

    public void mouseReleased(MouseEvent e) {
       saySomething("Mouse released; # of clicks: "
                    + e.getClickCount(), e);
    }

    public void mouseEntered(MouseEvent e) {
       saySomething("Mouse entered", e);
    }

    public void mouseExited(MouseEvent e) {
       saySomething("Mouse exited", e);
    }

    public void mouseClicked(MouseEvent e) {
       saySomething("Mouse clicked (# of clicks: "
                    + e.getClickCount() + ")", e);
    }

    void saySomething(String eventDescription, MouseEvent e) {
        textArea.append(eventDescription + " detected on "
                        + e.getComponent().getClass().getName()
                        + "." + newline);
    }
}

You can find more examples of mouse listeners in the following source files:

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).

int getX()
int getY()
Point getPoint()
Return the (x,y) position at which the event occurred, relative to the component that generated the event.
boolean isPopupTrigger()
Returns true if the mouse event should cause a popup menu to appear. Because popup triggers are platform dependent, if your program uses popup menus, you should call isPopupTrigger for all mouse-pressed and mouse-released events generated by components over which the popup can appear. See [PENDING] for more information about popup menus.

The MouseEvent class inherits the following handy method from ComponentEvent(in the API reference documentation).

Component getComponent
Returns the component that generated the event. You can use this method instead of the getSource method.

The MouseEvent class inherits many useful methods from InputEvent(in the API reference documentation):

void consume()
Causes the event not to be processed by the component's peer. You might use this method to discard letters typed into a text field that accepts only numbers. [PENDING: Update for SWING. Does this still exist? Not mention it anymore?]
int getWhen()
Returns the timestamp of when this event occurred. The higher the timestamp, the more recently the event occurred.

boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
Returns the state of individual modifier keys at the time the event was generated.

int getModifiers()
Returns the state of all the modifier keys and mouse buttons when the event was generated. You can use this method to determine which mouse button was pressed (or newly released) when a mouse event was generated. The InputEvent class defines these constants for use with the getModifiers method: ALT_MASK, BUTTON1_MASK, BUTTON2__MASK, BUTTON3_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. For example, the following expression is true if the right button was pressed:
(mouseEvent.getModifiers() & InputEvent.BUTTON3_MASK)
== InputEvent.BUTTON3_MASK
The SwingUtilities(in the API reference documentation) class contains convenience methods for determining whether a particular mouse button has been pressed:
static boolean isLeftMouseButton(MouseEvent)
static boolean isMiddleMouseButton(MouseEvent)
static boolean isRightMouseButton(MouseEvent)


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners