by Dinesh Thakur Category: Swing

Mouse event occurs when a mouse related activity is performed on a component such as clicking, dragging, pressing, moving or releasing a mouse etc. Objects representing mouse events are created from MouseEvent class.

There are two listener interfaces corresponding to the MouseEvent Class. These include MouseListener and MouseMotionListener interface. Each listener for MouseEvent should implement the appropriate interface.


Mouse Event 




void mouseClicked (MouseEvent e)

Invoked when the mouse button has been clicked (pressed and released) on a component

void mouseEntered (MouseEvent e)

Invoked when the mouse pointer enters a component

void mouseExited (MouseEvent e)

Invoked when the mouse pointer exits a component

void mousePressed (MouseEvent e)

Invoked when a mouse button has been pressed on a component

void mouseReleased (MouseEvent e)

Invoked when a mouse button has been released on a component

void mouseDragged (MouseEvent e)

Invoked when a mouse button is pressed on a component and then dragged

void mouseMoved (MouseEvent e)

Invoked when the mouse pointer has been moved onto a component but no buttons have been pressed


import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
class MouseListenerExample extends JFrame implements MouseListener
       JLabel lblData;
       JTextArea txtData;
         JPanel panel1 = new JPanel(new FlowLayout());
         JPanel panel2 = new JPanel(new FlowLayout());
         lblData = new JLabel("Press,Release or Click the Mouse on the txtArea to see x,y Coordinates");
         txtData = new JTextArea(20,30);
       public void mousePressed(MouseEvent e)
         String s= "x-Corrdinate = " + e.getX() + "y-Coordinate = " + e.getY();
         System.out.println("Mouse Pressed");
       public void mouseReleased(MouseEvent e)
         String s = "x-Coordinate = " + e.getX() + "y-Coordinate = " + e.getY();
         System.out.println("Mouse Released");
       public void mouseClicked(MouseEvent e)
         String s= "X-Corrdinate = " + e.getX() + " y-Coordinate = " + e.getY();
         System.out.println("Mouse Clicked");
         public void mouseEntered(MouseEvent e)
              System.out.println("Mouse Entered");
         public void mouseExited(MouseEvent e)
              System.out.println("Mouse Exited");
       class MouseListenerJavaExample
         public static void main(String[] args)
            MouseListenerExample frame = new MouseListenerExample();
            frame.setTitle(" Mouse Listener Java Swing Example");

MouseListener in Java Swing Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles