1. Technology

How to Handle Mouse Events

By

1 of 5

How to Handle Mouse Events

Handling mouse events in Java is split between three different event listeners. The MouseListener interface is used to track when a mouse is entering or leaving the area occupied by a graphical component, and when a the mouse button is pressed and released. The MouseMotionListener is used to track the mouse cursor as it is pressed and dragged or just moves around a graphical component's area. Finally, the MouseWheelListener tracks the movement of a mouse wheel. 

This step-by-step article will implement all three interfaces into a simple graphical user interface. Two JLabels will provide the focus the MouseListener and MouseMotionListener interfaces and a JScrollPane will be used for the MouseWheelListener interface.

The MouseListener Interface

To handle mouse clicks you need to have a class that implements the MouseListener interface. The class will need to implement the five methods declared by the MouseListener interface:

public interface MouseListener{
   public void mouseClicked(MouseEvent e);

   public void mouseEntered(MouseEvent e);

   public void mouseExited(MouseEvent e);

   public void mousePressed(MouseEvent e);

   public void mouseReleased(MouseEvent e);

}

The five mouse methods follow the typical behavior of a mouse. The mouseEntered method is called when the mouse cursor enters the area of the graphical component. Likewise, the mouseExited method is called when the mouse cursor leaves the area of the graphical component. The three other methods track what happens when a user uses the mouse button - the mouse button is pressed down (mousePressed method) followed by the release of the mouse button (mouseReleased method) which equates to the mouse being clicked  (mouseClicked method). 

The MouseEvent Object

Each of the five methods of the MouseListener interface is passed a MouseEvent object when they are called. The MouseEvent object contains information about the mouse event that has just occurred:

  • which mouse button was clicked (i.e., left, right or middle).
  • the location of where the mouse click took place - this can be relation to the screen, or the component, and can be split into the X and Y coordinates.
  • whether any keys were also being pressed along with the mouse click - used to capture modifying keys (e.g., SHIFT + left mouse click).
  • the number of clicks of the mouse button.
  1. About.com
  2. Technology
  3. Java
  4. Create User Interfaces
  5. Handling Events
  6. How to Handle Mouse Events

©2014 About.com. All rights reserved.