The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Creating a GUI with JFC/Swing
Lesson: Writing Event Listeners

How to Write a Mouse-Motion Listener

Mouse-motion events tell you when the user uses the mouse (or a similar input device) to move the onscreen cursor. For information on listening for other kinds of mouse events, such as clicks, see How to Write a Mouse Listener. If your program needs to detect both mouse events and mouse-motion events, you can use Swing's convenient MouseInputAdapter class, which implements both MouseListener and MouseMotionListener.

The following applet contains a mouse-motion listener. It's exactly like the applet in How to Write a Mouse Listener, except for substituting MouseMotionListener for MouseListener, implementing the mouseDragged and mouseMoved methods instead of the mouse listener methods, and displaying coordinates instead of numbers of clicks. You can find the applet's code in MouseMotionEventDemo.java(in a .java source file) and BlankArea.java(in a .java source file).

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-moved events.
  2. Press and hold the mouse button, and then move the mouse so that the cursor is outside the yellow rectangle.
    You'll see mouse-dragged events.

Here is the code that implements the mouse-motion event handling:
public class MouseMotionEventDemo extends JApplet 
                                  implements MouseMotionListener {
    //...in initialization code:
        //Register for mouse events on blankArea and applet (panel).
        blankArea.addMouseMotionListener(this);
        addMouseMotionListener(this);
        ...
    }

    public void mouseMoved(MouseEvent e) {
       saySomething("Mouse moved", e);
    }

    public void mouseDragged(MouseEvent e) {
       saySomething("Mouse dragged", e);
    }

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

A more interesting example is SelectionDemo, which is discussed in Arguments to the repaint Method(in the Creating a GUI with JFC/Swing trail). The program draws a rectangle illustrating the user's current dragging. To do this, it must implement an event handler for three kinds of mouse events: mouse presses, mouse drags, and mouse releases. To be informed of all these events, the handler must implement both the MouseListener and MouseMotionListener interfaces, and be registered as both a mouse listener and a mouse-motion listener. To avoid having to define empty methods, the handler doesn't implement either listener interface directly. Instead, it extends MouseInputAdapter, as the following code snippet shows.

...//where initialization occurs:
    MyListener myListener = new MyListener();
    addMouseListener(myListener);
    addMouseMotionListener(myListener);
...
class MyListener extends MouseInputAdapter {
    public void mousePressed(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        currentRect = new Rectangle(x, y, 0, 0);
        updateDrawableRect(getWidth(), getHeight());
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        updateSize(e);
    }

    public void mouseReleased(MouseEvent e) {
        updateSize(e);
    }

    void updateSize(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        ...
        repaint(...);
    }
}

The Mouse-Motion Event API

The MouseMotionListener(in the API reference documentation) interface and its corresponding adapter class, MouseMotionAdapter(in the API reference documentation), contain these methods:
void mouseDragged(MouseEvent)
Called in response to the user moving the mouse while holding a mouse button down. This event is fired by the component that fired the most recent mouse-pressed event, even if the cursor is no longer over that component.
void mouseMoved(MouseEvent)
Called in response to the user moving the mouse with no mouse buttons pressed. This event is fired by the component that's currently under the cursor.
Each mouse-motion event method has a single parameter -- and it's not called MouseMotionEvent! Instead, each mouse-motion event method has a MouseEvent argument. See The Mouse Event API for information about using MouseEvent objects.

Examples that Use Mouse-Motion Listeners

The following table lists the examples that use mouse-motion listeners.

Example Where Described Notes
MouseMotionEventDemo This section Reports all mouse motion events that occur within a blank panel to demonstrate the circumstances under which mouse motion events are fired.
LayeredPaneDemo and
LayeredPaneDemo2
How to Use Layered Panes(in the Creating a GUI with JFC/Swing trail) Moves an image of Duke around within a layered pane in response to mouse motion events.
SelectionDemo Arguments to the repaint Method(in the Creating a GUI with JFC/Swing trail) An applet that lets the user drag a rectangle to select a portion of an image. Uses a subclass of MouseInputAdapter to listen to both mouse events and mouse-motion events.
GlassPaneDemo How to Use Root Panes(in the Creating a GUI with JFC/Swing trail) Uses a subclass of MouseInputAdapter to listen to mouse events and mouse-motion events on the root pane's glass pane. Redispatches the events to underlying components.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form