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
Is part of the java.awt.event package
Is used to construct MouseEvent objects. Such objects are automatically fired when a mouse action occurs within a component. These actions are categorized as either simple mouse events or mouse motion events as follows:
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.
Has many methods. The two most frequently used are:
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
Is part of the java.awt.event package
Is a listener interface for receiving simple mouse events
May be implemented by any class that has Component as an ancestor. The implementation is specified in the class header. For example,
public class MyApplet extends Applet implements MouseListener
begins the definition of an Applet class extension (MyApplet) that implements the MouseListener interface. Components that wish to be notified of simple mouse events must register their MouseListener. For example, if x is the reference of some component, you may register the current object as a MouseListener by coding:
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.
Has five required methods that MUST be defined by the implementing class. The methods are:
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
Is part of the java.awt.event package
Is a listener interface for receiving mouse motion events
May be implemented by any class that has Component as an ancestor. The implementation is specified in the class header. For example,
public class MyApplet extends Applet implements MouseMotionListener
begins the definition of an Applet class extension (MyApplet) that implements the MouseMotionListener interface. Components that wish to be notified of mouse motion events must register their MouseMotionListener. For example, if x is the reference of some component, you may register the current object as a MouseMotionListener by coding:
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.
Has two required methods that MUST be defined by the implementing class. The methods are:
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:
In order to handle all kinds of mouse events, the applet implements both the MouseListener and MouseMotionListener interfaces.
The applet has two Button components (surprise and clear) and a Canvas component (canvas).
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...
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.
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
Which of the following statements are true of what will happen when the user moves the mouse to touch a component? (choose two)
a MouseMotionEvent object will be fired
a MouseEvent object will be fired
if the component has registered an ActionListener, its actionPerformed() method will be called
if the component has registered a MouseListener, its mouseEntered() method will be called
if the component has registered a MouseListener, its mouseMoved() method will be called
Which of the following methods are defined within the MouseMotionListener interface?
mouseMoved()
mouseDragged()
both mouseMoved() and mouseDragged()
neither mouseMoved() or mouseDragged()
Which one of the following is not a method required by the MouseListener interface?
mouseExited()
mouseReleased()
mouseClicked()
mousePressed()
mouseMoved()
If e is the reference of a MouseEvent object, which one of the following statements is true?
calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the screen
calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the top-left corner of the component
calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the screen
calling e.getX() will return the x-axis coordinate of where the mouse event occurred relative to the bottom-left corner of the component
none of the above