Aqua Phoenix
     >>  Lectures >>  Java 4  


4.8 MouseListener and MouseMotionListener

MouseListener and MouseMotionListener are event handlers that capture fundamental mouse behavior, inluding the mouse moving over the screen at different coordinates, button clicks, presses, and releases, dragging behavior, and some others. Event handlers discussed above are merely extensions to these generic mouse listeners.

The Event Listeners from before merely captured singular events, like a click, or a selection. For more complicated graphical components, we would want to use Event Handlers that can tell us exactly where the mouse is, i.e. the coordinates of the Mouse, when the Mouse has moved, whether or not a mouse button is being pressed, etc. This type of information is necessary in order to develop a paint program, for example. Recall one of the first tools you used to learn about data types. The tool itself is programmed in Java. Each datanode has some x,y position, and whenever you select a datanode and move it, the x,y position changes. That particular tool uses a lot of MouseListeners, as it is entirely graphical with lots of user interaction.

The MouseMotionListener specifically detects dragging and moving behaviors, while the MouseListener detects clicking, pressing, releasing of buttons, as well as the mouse cursor entering and exiting the boundaries of the area that implements the listener.

4.8.1 Template for including Mouse listeners

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class mouseApplet extends Applet implements MouseListener, MouseMotionListener {

  public void mouseApplet() {


  // from MouseListener
  public void mouseClicked(MouseEvent e) { }
  public void mouseEntered(MouseEvent e) { }
  public void mouseExited(MouseEvent e) { }
  public void mousePressed(MouseEvent e) { }
  public void mouseReleased(MouseEvent e) { }

  // from MouseMotionListener
  public void mouseDragged(MouseEvent e) { }
  public void mouseMoved(MouseEvent e) { }

Because there are two mouse handlers, both interfaces must be included, if all mouse functionality is required. Otherwise, if the only desired functionality was to capture mouse clicks, then the MouseMotionListener need not be included.

The MouseEvent passed to all of the mouse handler methods can be used to extract the current mouse cursor position in terms of (x,y) relative to the component. It is important to note that positions are always relative to the component implementing the mouse listener. If a GUI contains several objects that implement mouse listeners, then each GUI component has its own (0,0) coordinate in the left-upper-hand corner of its own area.

X- and y- positions can be obtained as follows:

  public void mouseClicked(MouseEvent e) {

    int x = e.getX();
    int y = e.getY();


4.8.2 Example

The following is an example of an applet that implements both mouse handlers, and prints the current mouse operation on the applet: