Mouse event processing

 

Overview

Features for detecting and processing mouse events are part of the java.awt and java.awt.event packages. Any windows program or applet may easily incorporate mouse event processing.

 

The MouseEvent class

Simple mouse events:

A mouse button is pressed
A mouse button is released
A mouse button is clicked
The mouse enters a component
The mouse exits a component

Mouse motion events:

The mouse is moved
The mouse is dragged

In order to receive and process simple mouse events, a component must register a MouseListener. To receive and process mouse motion events, a component must register a MouseMotionListener. For example, if myCanvas is a Canvas object, the statements

myCanvas.addMouseListener(this);
myCanvas.addMouseMotionListener(this);

will register listeners for all mouse events that may be fired by the myCanvas component. All that remains is to implement the two interfaces and their required methods. This will be covered shortly.

Method

Usage

getX()

Returns the x-axis coordinate of the event relative to the top-left corner of the component

getY()

Returns the y-axis coordinate of the event relative to the top-left corner of the component

 

The MouseListener interface

x.addMouseListener(this);

When a simple mouse event occurs within component x, a MouseEvent object will be automatically fired to the relevant method within the listener object.

Method

Usage

mouseClicked()

Invoked when the mouse has been clicked on a component

mouseEntered()

Invoked when the mouse enters a component

mouseExited()

Invoked when the mouse exits a component

mousePressed()

Invoked when a mouse button has been pressed on a component

mouseReleased()

Invoked when a mouse button has been released on a component

Each of the above methods receives a MouseEvent object as a parameter and returns no value (is void). Consult the Java API for more details.

 

The MouseMotionListener interface

x.addMouseMotionListener(this);

When a mouse motion event occurs within component x, a MouseEvent object will be automatically fired to the relevant method within the listener object.

Method

Usage

mouseDragged()

Invoked when a mouse button is pressed on a component and the mouse is moved with the button down

mouseMoved()

Invoked when the mouse has been moved on a component with no buttons down

Each of the above methods receives a MouseEvent object as a parameter and returns no value (is void). Consult the Java API for more details.

 

The MouseAdapter and the MouseMotionAdapter classes

Rather than implement the MouseListener or MouseMotionListener interfaces, a class may choose to extend the MouseAdapter or the MouseMotionAdapter class. These classes contain definitions for all required interface methods so that only the methods of interest must be coded to override those inherited.

The technique is most often used when registering and defining an inner listener. For example, if x is the reference of some component, you may register and define its listener for handling mouse movement by coding:

x.addMouseMotionListener(
  new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent e) {
     
custom code goes here...
    }
  }
);

When the mouse is moved within component x, a MouseEvent object will be automatically fired to the custom code defined within this inner listener.

 

A sample applet that uses mouse events

This applet can be used to draw small blue dots. To draw a dot, just click the mouse anywhere within the central portion of the applet's panel. A button at the bottom of the applet panel can be clicked to clear the dots already drawn.

The applet's code is as follows:

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

public class App extends Applet implements ActionListener,
  MouseListener, MouseMotionListener {

  Button surprise = new Button("Click here to win $1 Million!");
  Button clear = new Button("Clear");
  Canvas canvas = new Canvas();

  public void init() {
    resize(400, 400);
    setLayout(new BorderLayout());
    surprise.setFont(new Font("SanSerif", Font.BOLD, 18));
    surprise.addMouseListener(this);
    add(surprise, BorderLayout.NORTH);
    canvas.setForeground(Color.blue);
    canvas.setFont(new Font("SanSerif", Font.PLAIN, 10));
    canvas.addMouseListener(this);
    canvas.addMouseMotionListener(this);
    add(canvas);
    clear.addActionListener(this);
    add(clear, BorderLayout.SOUTH);
  }

  // Method required by the ActionListener interface.

  public void actionPerformed(ActionEvent e) {
    Graphics g = canvas.getGraphics();
    g.setColor(canvas.getBackground());
    g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
  }

  // Methods required by the MouseListener interface.

  public void mouseClicked(MouseEvent e) {
    if (e.getSource().equals(canvas)) {
      int originX = e.getX() - 10;
      int originY = e.getY() - 10;
      Graphics g = canvas.getGraphics();
      g.fillOval(originX, originY, 20, 20);
    }
  }
  public void mouseEntered(MouseEvent e) {
    if (e.getSource().equals(surprise))
      surprise.setVisible(false);
    else
      surprise.setVisible(true);
  }
  public void mouseExited(MouseEvent e) {}
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}

  // Methods required by the MouseMotionListener interface.

  public void mouseMoved(MouseEvent e) {
    showPosition(e);
  }
  public void mouseDragged(MouseEvent e) {
    showPosition(e);
  }

  // Custom method to display the current mouse position within the
  // canvas component.

  private void showPosition(MouseEvent e) {
    Graphics g = canvas.getGraphics();
    String currentPosition =
      new String("x = " + e.getX() + ", y = " + e.getY());
    g.clearRect(2, canvas.getHeight()-17, 80, 17);
    g.setColor(Color.black);
    g.drawString(currentPosition, 2, canvas.getHeight()-2);
  }
}

Notes:

  1. In order to handle all kinds of mouse events, the applet implements both the MouseListener and MouseMotionListener interfaces. 

  2. The applet has two Button components (surprise and clear) and a Canvas component (canvas).

  3. No, you're NEVER going to get that $1 million. The surprise button has a registered MouseListener and the MouseEntered() method hides the button every time you enter it and makes it reappear every time you enter some other component having a registered MouseListener interface (canvas). Sorry...

  4. Drawing of dots occurs within the Canvas object (canvas). It has a registered MouseListener, so a mouse click within the component fires a MouseEvent object to the mouseClicked() method. The method determines the location of the click, obtains the context of the component, and draws a blue dot at that location.

  5. Whenever the mouse is moved or dragged within canvas, its position is displayed at the bottom-right corner of the component. The registered MouseMotionListener makes this possible by firing a MouseEvent object to either the mouseMoved() or the mouseDragged() method. These methods pass the object along to a custom method of the applet's class named showPosition() which builds a text string representing the current mouse position and displays it via the component's context.

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. Which of the following statements are true of what will happen when the user moves the mouse to touch a component?  (choose two)

  1. a MouseMotionEvent object will be fired

  1. a MouseEvent object will be fired

  2.  if the component has registered an ActionListener, its actionPerformed() method will be called

  3.  if the component has registered a MouseListener, its mouseEntered() method will be called

  4. if the component has registered a MouseListener, its mouseMoved() method will be called

  1. Which of the following methods are defined within the MouseMotionListener interface?

  1. mouseMoved()

  1. mouseDragged()

  2. both  mouseMoved() and  mouseDragged()

  3. neither  mouseMoved() or  mouseDragged()

  1. Which one of the following is not a method required by the MouseListener interface?

    1. mouseExited()

    1. mouseReleased()

    2. mouseClicked()

    3. mousePressed()

    4. mouseMoved()

  1. If e is the reference of a MouseEvent object, which one of the following statements is true?

  1. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the screen

  2. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the component

  3. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the screen

  4. calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the component

  5. none of the above