Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 36: Mouse event processing

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 36 by Jon Huhtala: 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

  • 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, 1Cool);
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


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy