Owl Sams Teach Yourself Java 2 in 21 Days

Day 13: Handling Mouse Clicks

EVENT HANDLING

Like all of the applets in the book, the Spots and Lines projects use Java 1.0 techniques so they can run on the widest possible audience of browsers. When you compile these programs, "deprecation warning" messages will be displayed because better techniques are available in Java 2 to handle user events such as mouse clicks.

The programs in the book will compile and run successfully, but for those who want an early introduction to Java 2 event-handling, this tutorial describes how the Spots and Lines examples can be rewritten using the new techniques.

Note: This page will make more sense if you've already created the Spots and Lines examples in the book.

The preferred way to handle mouse events in Java is to use an event listener, a technique introduced fully in Day 21, "Handling User Events with Swing."

Event listeners are interfaces, groups of related methods that indicate a class has a certain kind of behavior. (You worked with interfaces on Day 10, "Adding Images, Animation, and Sound."). All of the listener interfaces are part of java.awt.event, the event-handling package.

Mouse input is received by two listener interfaces: MouseListener, which handles mouse clicks and two kinds of mouse movement, and MouseMotionListener, which handles all other kinds of mouse movement.

HANDLING MOUSE CLICKS

The MouseListener interface includes six methods for receiving mouse input:

public void mouseClicked(MouseEvent evt) {
   // called when the main mouse button is
   // clicked and released

}

public void mousePressed(MouseEvent evt) {
   // called when the button is clicked
}

public void mouseReleased(MouseEvent evt) {
    // called when the button is released
}

public void mouseEntered(MouseEvent evt) {
    // called when the mouse moves over
    // the component receiving mouse events
    // (such as an applet window)
}

public void mouseExited(MouseEvent evt) {
    // called when the mouse moves away
    // from the component receiving mouse
    // events

}

Each of these methods has a single argument: MouseEvent, another class in the java.awt.event package. This class includes several methods that are used to find out more about what the user did with the mouse:

  • getX(): the x position where the mouse was clicked, returned as an integer value
  • getY(): the y position where the mouse was clicked, as an integer
  • getClickCount(): the number of times the mouse was clicked, as an integer

As you may recall from Day 10, a Java class makes use of an interface by using the implements keyword in the class declaration, as in the following example:

public class Spots extends java.applet.Applet implements MouseListener {
    // ...
}

When a class implements an interface, it must include all methods of that interface, even if you don't need some of them. If you are rewriting the Spots applet, the only mouse event you are interested in is mouseClicked(MouseEvent), because the applet waits for a mouse click and draws a spot at the position of that click.

The following mouseClicked() method draws a spot at the position of a mouse click until the number of spots equals the value of the MAXSPOTS variable:

public void mouseClicked(MouseEvent evt) {
    if (currspots < MAXSPOTS) {
        addspot(evt.getX(), evt.getY());
    } else {
        System.out.println("Too many spots.");
    }
}

As you can see, this method isn't much different from the mouseDown() method in the Spots example. You receive all information about the mouse-click in the MouseEvent argument, and then call getX() and getY() to get the (x,y) position of the click.

The other methods of the MouseListener interface can be added as do-nothing methods such as the following:

public void mousePressed(MouseEvent evt) {
    // do nothing
}

When you are handling user events by using a listener class like MouseListener, the user interface component that receives the events must be registered as a listener by calling the component's addMouseListener(Object) method. The Object used as an argument is the component that implements the MouseListener interface. If you use the this keyword as this argument, it refers to the current class.

For example, the Spots applet is a component that receives mouse events. To register it as a listener, the following statement can be used in the applet's init() method:

addMouseListener(this);

The NewSpots.java file contains the source code for an applet that uses these techniques in place of the ones described in the book. NewSpots.html is a simple Web page that contains the applet. Load this page into appletviewer to see that it functions exactly like the Spots applet.

HANDLING MOUSE MOTION

The MouseListener interface handles two kinds of mouse motion: the moment a mouse is first moved over a user interface component and the moment it is first moved off that component. These events are handled by the mouseEntered() and mouseExited() methods, respectively.

In the NewSpots example, the mouseEntered() method is called when you first move the mouse cursor over the applet window. When you move the cursor off the applet window, the mouseExited() method is called. (Neither of these methods does anything in NewSpots, so nothing happens as a result of these events.)

The MouseMotionListener interface includes two methods for other kinds of mouse movement:

public void mouseDragged(MouseEvent evt) {
    // called when the mouse is moved while
    // a button is pressed down
}

public void mouseMoved(MouseEvent evt) {
    // called when the mouse is moved while
    // no buttons are pressed down
}


Both of these methods tracks mouse movement continuously, which differentiates them from the methods of the MouseListener interface. Classes that handle these events must implement the MouseMotionListener interface and use a component's addMouseMotionListener(Object) method to register as a listener.

The NewLines.java file contains the source code for an applet that implements both the MouseListener and MouseMotionListener interfaces to recreate the Lines example from the book. NewLines.html is a simple Web page that contains the applet. Load this page into appletviewer to see that it functions exactly like the Lines applet.

Use the following links to see Sun's official documentation for these classes and interfaces:

Return to Day 13