Java MouseListener

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java MouseListener Interface

The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.

Methods of MouseListener interface

The signature of 5 methods found in MouseListener interface is given below:

  1. public abstract void mouseClicked(MouseEvent e);  
  2. public abstract void mouseEntered(MouseEvent e);  
  3. public abstract void mouseExited(MouseEvent e);  
  4. public abstract void mousePressed(MouseEvent e);  
  5. public abstract void mouseReleased(MouseEvent e);  

Java MouseListener Example

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class MouseListenerExample extends Frame implements MouseListener{  
  4.     Label l;  
  5.     MouseListenerExample(){  
  6.         addMouseListener(this);  
  7.           
  8.         l=new Label();  
  9.         l.setBounds(20,50,100,20);  
  10.         add(l);  
  11.         setSize(300,300);  
  12.         setLayout(null);  
  13.         setVisible(true);  
  14.     }  
  15.     public void mouseClicked(MouseEvent e) {  
  16.         l.setText("Mouse Clicked");  
  17.     }  
  18.     public void mouseEntered(MouseEvent e) {  
  19.         l.setText("Mouse Entered");  
  20.     }  
  21.     public void mouseExited(MouseEvent e) {  
  22.         l.setText("Mouse Exited");  
  23.     }  
  24.     public void mousePressed(MouseEvent e) {  
  25.         l.setText("Mouse Pressed");  
  26.     }  
  27.     public void mouseReleased(MouseEvent e) {  
  28.         l.setText("Mouse Released");  
  29.     }  
  30. public static void main(String[] args) {  
  31.     new MouseListenerExample();  
  32. }  
  33. }  

Output:

java awt mouselistener example 1

Java MouseListener Example 2

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class MouseListenerExample2 extends Frame implements MouseListener{  
  4.     MouseListenerExample2(){  
  5.         addMouseListener(this);  
  6.           
  7.         setSize(300,300);  
  8.         setLayout(null);  
  9.         setVisible(true);  
  10.     }  
  11.     public void mouseClicked(MouseEvent e) {  
  12.         Graphics g=getGraphics();  
  13.         g.setColor(Color.BLUE);  
  14.         g.fillOval(e.getX(),e.getY(),30,30);  
  15.     }  
  16.     public void mouseEntered(MouseEvent e) {}  
  17.     public void mouseExited(MouseEvent e) {}  
  18.     public void mousePressed(MouseEvent e) {}  
  19.     public void mouseReleased(MouseEvent e) {}  
  20.       
  21. public static void main(String[] args) {  
  22.     new MouseListenerExample2();  
  23. }  
  24. }  

Output:

java awt mouselistener example 2