JavaHow to Use Mouse Listeners in Java

How to Use Mouse Listeners in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java programming tutorial

Java enables programmers to listen for events from a mouse (or a similar device, such as a touchpad). There are three different interfaces that developers can implement for different actions from a mouse input. These interfaces are separated in this manner because tracking the mouse’s motion uses more system resources than other mouse events. In this programming tutorial, we will learn how to implement various mouse event listeners in your graphical Java applications.

Before we get started, you may want to brush up on your event listening skills. If so, we have a great guide to working with Java Event Listeners you should check out.

What is a Mouse Listener in Java?

In Java, the MouseListener interface registers an event whenever the mouse cursor is moved into the area of a component listening for mouse events. To add this listener to a component, developers can use the addMouseListener(instanceOfHandler) method.

MouseListener has five methods programmers can use to detect when the mouse:

  • Has been clicked: mouseClicked(MouseEvent e)
  • Has been pressed: mousePressed(MouseEvent e)
  • Has been released: mouseReleased(MouseEvent e)
  • Has entered the component region: mouseEntered(MouseEvent e)
  • Has left the component region: mouseExited(MouseEvent e)

The example code below shows how to apply each of these five MouseListener methods:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MouseListenerHandler implements MouseListener{


   JFrame frame = new JFrame();
   Container pane = frame.getContentPane();


   MouseListenerHandler(){
       pane.addMouseListener(this);


       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(375,450);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }


   public void mouseClicked(MouseEvent e) {


       int x = e.getClickCount();
       System.out.println("You CLICKED the mouse " + x + " times.");
   }


   public void mouseEntered(MouseEvent e) {
       pane.setBackground(Color.YELLOW);
   }


   public void mouseExited(MouseEvent e) {
       pane.setBackground(Color.MAGENTA);
   }


   public void mousePressed(MouseEvent e) {
       System.out.println("You have PRESSED the mouse");
   }


   public void mouseReleased(MouseEvent e) {


       int a = e.getX();
       int b = e.getY();
       System.out.println("You have RELEASED the mouse at (" + a + "," + b + ") - (X,Y)");
   }
     
   public static void main(String args[]){
      
       new MouseListenerHandler();
  
   }
}

Running this code in your code editor or integrated development environment (IDE) produces the following output:

Java Mouse Events

Read: Top Productivity Tools for Java Developers

Java Mouse-Motion Listener

The MouseMotionListener interface allows developers to monitor the cursor movements made by the mouse. It has two methods which can enable you to know when a user has:

  • Pressed and dragged the mouse: mouseDragged(MouseEvent e)
  • Moved the mouse with pressing it: mouseMoved(MouseEvent e)

The example Java code below prints out a message on your terminal whenever a user makes any of the above actions:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MotionHandler extends JPanel implements MouseMotionListener{


   JFrame frame = new JFrame();
   Container pane = frame.getContentPane();
 
   MotionHandler(){
       pane.addMouseMotionListener(this);


       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(400,450);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
  
   public void mouseDragged(MouseEvent e) {
       System.out.println("You have DRAGGED the mouse");
   }


   public void mouseMoved(MouseEvent e) {
       System.out.println("You have MOVED the mouse");
   }


   public static void main(String args[]){  
       new MotionHandler();
  
   }
}

Java Mouse-Wheel Listener

In Java, the MouseWheelListener is an interface used to listen for the rotation of the mouse wheel. Before going any further, it is important to note that not all mouse-like input devices provide for mouse-wheel rotations.

The MouseWheelListener has only one method: mouseWheelMoved( MouseWheelEvent e). Developers can use this method to implement some logic like telling which direction the mouse wheel has been moved and by how much.

The MouseWheelEvent class has some useful methods that can give programmers information about the rotations. Some of those methods include:

  • getWheelRotation(): returns an integer number of clicks for the mouse rotation
  • getPreciseWheelRotation(): returns a double-precision value for the clicks of a mouse rotation. This can be important for when incomplete rotations are made

You can find the complete list of mouse listener methods from the official Oracle API docs for Java.

The code example below prints out the number of clicks for the mouse rotation in the graphical component for which you are listening for mouse events (in this case the panel of the JFrame).

If you try rotating the mouse-wheel both forwards and backwards, you will notice that positive and negative values are produced for each of the corresponding directions. Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MouseWheelHandler implements MouseWheelListener{


   JFrame frame = new JFrame();
   Container pane = frame.getContentPane();


   MouseWheelHandler(){
       pane.addMouseWheelListener(this);


       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(390,450);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }


   public void mouseWheelMoved(MouseWheelEvent e) {
       System.out.println(e.getWheelRotation());
   }
    
   public static void main(String args[]){
      
       new MouseWheelHandler();
  
   }
}

Final Thoughts on Java Mouse Listeners

In this Java programming tutorial, we learned that mouse events can be captured from a mouse or a similar input device. There are three different mouse listeners that programmers can use for mouse events, which include: MouseListeners, MouseMotionListener, and MouseWheelListener. Remember, too, that the MouseWheelListener may function differently depending on the user’s input device.

Read: Top Java Frameworks

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories