MouseListener and MouseMotionListener Example

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

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 Reply

Your email address will not be published. Required fields are marked *