MouseListener and MouseMotionListener in Java
Last Updated :
30 Jul, 2024
MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse events
are of two types. MouseListener handles the events when the mouse is not in motion. While MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract functions that represent these five events.
The abstract functions are :
- void mouseReleased(MouseEvent e) : Mouse key is released
- void mouseClicked(MouseEvent e) : Mouse key is pressed/released
- void mouseExited(MouseEvent e) : Mouse exited the component
- void mouseEntered(MouseEvent e) : Mouse entered the component
- void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate. There are two abstract functions that represent these two events. The abstract functions are :
- void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the component and dragged. Events are passed until the user releases the mouse button.
- void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one point to another within the component, without pressing any mouse buttons.
The following programs are a illustration of MouseListener and MouseMotionListener.
1. Program to handle MouseListener events
Java
// Java program to handle MouseListener events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseListener {
// Jlabels to display the actions of events of mouseListener
// static JLabel label1, label2, label3;
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");
// set the size of the frame
f.setSize(600, 100);
// close the frame when close button is pressed
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create a new panel
JPanel p = new JPanel();
// set the layout of the panel
p.setLayout(new FlowLayout());
// initialize the labels
label1 = new JLabel("no event ");
label2 = new JLabel("no event ");
label3 = new JLabel("no event ");
// create an object of mouse class
Mouse m = new Mouse();
// add mouseListener to the frame
f.addMouseListener(m);
// add labels to the panel
p.add(label1);
p.add(label2);
p.add(label3);
// add panel to the frame
f.add(p);
f.show();
}
// getX() and getY() functions return the
// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user
// this function is invoked when the mouse is pressed
public void mousePressed(MouseEvent e)
{
// show the point where the user pressed the mouse
label1.setText("mouse pressed at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse is released
public void mouseReleased(MouseEvent e)
{
// show the point where the user released the mouse click
label1.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse exits the component
public void mouseExited(MouseEvent e)
{
// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse enters the component
public void mouseEntered(MouseEvent e)
{
// show the point through which the mouse entered the frame
label2.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse is pressed or released
public void mouseClicked(MouseEvent e)
{
// getClickCount gives the number of quick,
// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label3.setText("mouse clicked at point:"
+ e.getX() + " "
+ e.getY() + "mouse clicked :" + e.getClickCount());
}
}
Output :


Note : The following program might not run in an online compiler please use an offline IDE
Let's take another example on MouseListener,the question is:
Q. Write an applet which displays x and y co-ordinate in it's status bar whenever the user click anywhere in the Applet window.
Ans.
Note: This code is with respect to Netbeans IDE.
Java
//Program of an applet which
//displays x and y co-ordinate
//in it's status bar,whenever
//the user click anywhere in
//the applet window.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
//is current calling object) and
//second "this" represent
//listener(in this case it is GFG)
}
public void mouseClicked(MouseEvent m)
{
int x = m.getX();
int y = m.getY();
String str = "x =" +x+",y = "+y;
showStatus(str);
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
Output:
Output showing (x,y) in status bar
Modification: Now our aim is to improve above program so that co-ordinates should display at that point only where click has been made
Note: This code is with respect to Netbeans IDE.
Java
//Co-ordinates should display
//at that point only wherever
//there is click on canvas
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
// is current calling object) and
// second "this" represent listener
//(in this case it is GFG)
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint(); // we have made this
//call because repaint() will
//call paint() method for us.
//If we comment out this line,
//then we will see output
//only when focus is on the applet
//i.e on maximising the applet window
//because paint() method is called
//when applet screen gets the focus.
//repaint() is a method of Component
//class and prototype for this method is:
//public void repaint()
}
public void mouseEntered(MouseEvent m)
//over-riding all the methods given by
// MouseListener
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
}
Output
Output showing (x,y) in canvas
Now one more unusual thing will come in output which is that, we will not able to see previous co-ordinates.But why?
In Java, before calling paint() method, it calls one more method which is update() and it do the following things:
- it repaints the applet background with current color.
- it then calls paint().
Now to see previous co-ordinates as well:
we have to over-ride update() method also and it's prototype is similar to paint().
Further Modification To see previous co-ordinates as well:
Note: This code is with respect to Netbeans IDE.
Java
//Co-ordinates should display
//at that point only wherever
//there is click on canvas and also
//able to see the previous coordinates
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void update(Graphics g)
{
paint(g);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint();
}
public void mouseEntered(MouseEvent m)
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
}
Output
Output showing previous co-ordinate as well
2. Program to handle MouseMotionListener events
Java
// Java Program to illustrate MouseMotionListener events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseMotionListener {
// Jlabels to display the actions of events of MouseMotionListener
static JLabel label1, label2;
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseMotionListener");
// set the size of the frame
f.setSize(600, 400);
// close the frame when close button is pressed
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create new panel
JPanel p = new JPanel();
// set the layout of the panel
p.setLayout(new FlowLayout());
// initialize the labels
label1 = new JLabel("no event ");
label2 = new JLabel("no event ");
// create an object of mouse class
Mouse m = new Mouse();
// add mouseListener to the frame
f.addMouseMotionListener(m);
// add labels to the panel
p.add(label1);
p.add(label2);
// add panel to the frame
f.add(p);
f.show();
}
// getX() and getY() functions return the
// x and y coordinates of the current
// mouse position
// invoked when mouse button is pressed
// and dragged from one point to another
// in a component
public void mouseDragged(MouseEvent e)
{
// update the label to show the point
// through which point mouse is dragged
label1.setText("mouse is dragged through point "
+ e.getX() + " " + e.getY());
}
// invoked when the cursor is moved from
// one point to another within the component
public void mouseMoved(MouseEvent e)
{
// update the label to show the point to which the cursor moved
label2.setText("mouse is moved to point "
+ e.getX() + " " + e.getY());
}
}
Output :


3. Java program to illustrate MouseListener and MouseMotionListener events
simultaneously
Java
// Java program to illustrate MouseListener
// and MouseMotionListener events
// simultaneously
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseMotionListener, MouseListener {
// Jlabels to display the actions of events of MouseMotionListener and MouseListener
static JLabel label1, label2, label3, label4, label5;
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener and MouseMotionListener");
// set the size of the frame
f.setSize(900, 300);
// close the frame when close button is pressed
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create new panel
JPanel p = new JPanel();
JPanel p1 = new JPanel();
// set the layout of the frame
f.setLayout(new FlowLayout());
JLabel l1, l2;
l1 = new JLabel("MouseMotionListener events :");
l2 = new JLabel("MouseLIstener events :");
// initialize the labels
label1 = new JLabel("no event ");
label2 = new JLabel("no event ");
label3 = new JLabel("no event ");
label4 = new JLabel("no event ");
label5 = new JLabel("no event ");
// create an object of mouse class
Mouse m = new Mouse();
// add mouseListener and MouseMotionListenerto the frame
f.addMouseMotionListener(m);
f.addMouseListener(m);
// add labels to the panel
p.add(l1);
p.add(label1);
p.add(label2);
p1.add(l2);
p1.add(label3);
p1.add(label4);
p1.add(label5);
// add panel to the frame
f.add(p);
f.add(p1);
f.show();
}
// getX() and getY() functions return the
// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user
// MouseMotionListener events
// invoked when mouse button is pressed
// and dragged from one point to another
// in a component
public void mouseDragged(MouseEvent e)
{
// update the label to show the point
// through which point mouse is dragged
label1.setText("mouse is dragged through point "
+ e.getX() + " " + e.getY());
}
// invoked when the cursor is moved from
// one point to another within the component
public void mouseMoved(MouseEvent e)
{
// update the label to show the point to which the cursor moved
label2.setText("mouse is moved to point "
+ e.getX() + " " + e.getY());
}
// MouseListener events
// this function is invoked when the mouse is pressed
public void mousePressed(MouseEvent e)
{
// show the point where the user pressed the mouse
label3.setText("mouse pressed at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse is released
public void mouseReleased(MouseEvent e)
{
// show the point where the user released the mouse click
label3.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse exits the component
public void mouseExited(MouseEvent e)
{
// show the point through which the mouse exited the frame
label4.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse enters the component
public void mouseEntered(MouseEvent e)
{
// show the point through which the mouse entered the frame
label4.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse is pressed or released
public void mouseClicked(MouseEvent e)
{
// getClickCount gives the number of quick,
// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label5.setText("mouse clicked at point:"
+ e.getX() + " "
+ e.getY() + "mouse clicked :" + e.getClickCount());
}
}
output :


MouseListener vs MouseMotionListener
- MouseListener: MouseListener events are invoked when the mouse is not in motion and is stable . It generates events such as mousePressed, mouseReleased, mouseClicked, mouseExited and mouseEntered (i.e when the mouse buttons are pressed or the mouse enters or exits the component). The object of this class must be registered with the component and they are registered using addMouseListener() method.
- MouseMotionListener: MouseMotionListener events are invoked when the mouse is in motion . It generates events such as mouseMoved and mouseDragged (i.e when the mouse is moved from one point to another within the component or the mouse button is pressed and dragged from one point to another ). The object of this class must be registered with the component and they are registered using addMouseMotionListener() method.
Similar Reads
Moving Ball Using Thread in Java
Prerequisites: Java.lang.Thread class in JavaMouseListener and MouseMotionListener in Java This is a simple Java code including the concept of Thread and Java AWT to implement three balls moving in a particular path in an AWT frame. In this implementation, three balls are taken in an AWT frame and h
3 min read
Java Swing | Simple User Registration Form
Swing is a part of the JFC (Java Foundation Classes). Building Graphical User Interface in Java requires the use of Swings. Swing Framework contains a large set of components which allow a high level of customization and provide rich functionalities, and is used to create window-based applications.
5 min read
JavaFX | Rectangle and Rounded Rectangle with examples
Rectangle class is a part of JavaFX. Rectangle class creates a rectangle with specified width and height and position. By default Rectangle has sharp corners but the edges can be rounded by applying a arc height and width. Constructor : Rectangle(): creates a empty instance of rectangleRectangle(dou
4 min read
Java Swing | JSpinner
JSpinner is a part of javax.swing package. JSpinner contains a single line of input which might be a number or a object from an ordered sequence. The user can manually type in a legal data into the text field of the spinner. The spinner is sometimes preferred because they do not need a drop down lis
3 min read
JSwing | Create a Magnifying tool using Java Robot
Java Robot is a part of Java AWT (Abstract Window Toolkit ) package . Java Robot is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The purpose of using Java Robot is to gai
2 min read
Draw a ellipse and a rectangle in Java Applet
Java applets are application that can be executed in web browsers or applet viewers . We can draw shapes on the Java applet. In this article we will draw a ellipse on Java applet by two ways . By using the drawOval(int x, int y, int width, int height) or by using mathematical formula (X= A * sin a,
4 min read
How to Copy Text to the Clipboard in Java?
We will be going through some source code for a Java method that lets you copy texts to the clipboard of your operating system. Java provides a class called Clipboard, which is found in java.awt.data transfer. Clipboard provides important functionalities of the Graphical User Interface(GUI), namely
3 min read
JavaFX | Reflection Class
Reflection class is a part of JavaFX. The Reflection class is used to add a reflected image below the actual image of the input value. The Reflected image will not respond to mouse events or the containment methods on the input. Constructors of the class: Reflection(): Creates a new Reflection Objec
4 min read
Java Swing | Creating Custom Message Dialogs
Though Java Swing provides built-in message dialog to display messages, we can create custom message dialog by using JWindow and other Java Swing elements. The advantage of creating them is that they are highly customizable and we can add the desired look-and-feel and functionalities to them.In this
4 min read
Implementing Traffic Signal Using Java Swing Components
Create a  Button Group such that it contains three radio buttons Red, Yellow, Green when red is clicked you want to display âStopâ, when orange is clicked you want to display âreadyâ, when the green button is clicked Display âGoâ and also create a sample Traffic signal demo using rectangle and ovals
3 min read