MouseListener and MouseMotionListener Example


We did two separate programs on mouse event handling with MouseListener and MouseMotionListener. Now let us have an example implementing both mouse listener interfaces. It is very simple, but required to override 5 abstract methods of MouseListener and 2 abstract methods of MouseMotionListener.

To make the program simple, just I am changing the background color of the frame as per the mouse action performed. Remember there are 7 actions you can perform now (represented by 7 abstract methods).

MouseListener MouseMotionListener Example
import java.awt.*;
import java.awt.event.*;

public class MLandMML extends Frame implements MouseListener, MouseMotionListener 
{                      
  public MLandMML()
  {
    addMouseListener(this);
    addMouseMotionListener(this);

    setSize(300,300);
    setVisible(true);
  }                    
                      // override the 5 abstract methods of MouseListener
  public void mousePressed(MouseEvent e)
  {  
    setBackground(Color.red);
  }
  public void mouseReleased(MouseEvent e)
  {  
    setBackground(Color.green);
  }
  public void mouseClicked(MouseEvent e)
  {  
    setBackground(Color.green);
  }
  public void mouseEntered(MouseEvent e)
  {  
    setBackground(Color.darkGray);
  }
  public void mouseExited(MouseEvent e)
  {  
    setBackground(Color.orange);
  }
                     // override the 2 abstract methods of MouseMotionListener
  public void mouseMoved(MouseEvent e)
  {  
    setBackground(Color.cyan);
  }
  public void mouseDragged(MouseEvent e)
  {  
    setBackground(Color.magenta);
  }
  
  public static void main(String snrao[])
  {
    new MLandMML();
  }                                    
}                                   

public class MLandMML extends Frame implements MouseListener, MouseMotionListener

Observe, the frame implements both listeners. This is the advantage of multiple inheritance with interfaces in Java.

addMouseListener(this);
addMouseMotionListener(this);

It is necessary to register the frame with both the listeners, else, the event raised by mouse on the frame will not be handled by listeners.

MouseListener MouseMotionListener Example
Output screen of MouseListener MouseMotionListener Example

Leave a Comment

Your email address will not be published.