Handling MouseEvent with MouseListener Example

Handling MouseEvent with MouseListener Example

Java events are of two types – a) generated by frame, button etc. (AWT components) known as semantic events and b) generated by mouse, keyboard (Hardware components) known as low-level events. When you click a mouse, the mouse generates mouse event represented by class MouseEvent. Similarly, when you type a key on Keyboard, the key generates a key event represented by class KeyEvent and handled by KeyListener.

Generation of mouse events, again is of two types. If the mouse is stable (not moving) it generates MouseEvent and is handled by MouseListener and if the mouse is in motion, the mouse generates the same MouseEvent but handled by MouseMotionListener.

The mouse can generates five types of events (of course, when mouse stable only) and each type is represented by one abstract method of MouseListener. Following table illustrates.

Action Name Represented by abstract method of MouseListener
Mouse key is just pressed void mousePressed(MouseEvent)
Mouse key is released (after pressed) void mouseReleased(MouseEvent)
Mouse key is clicked void mouseClicked(MouseEvent)
When mouse enters a frame or MS Word window etc. void mouseEntered(MouseEvent)
When mouse exists a frame or MS Word window etc. (after entering) void mouseExited(MouseEvent)

This example illustrates how to handle the events when the mouse is stable using MouseListener by overriding the above 5 abstract methods. In this code, the mouse action is displayed as a label.


This method defined in class Frame links or registers the frame with the MouseListener. If this statement is omitted, MouseListener does not handle the events of mouse and thereby no actions.

Label component is explained in AWT Label – Alignment.

All the five abstract methods of MouseListener are overridden.

Output screen shown with one of the actions.


View All for Mouse Listener/Adapter, Mouse Motion Listener/Adapter, Key Listener/Adapter

Leave a Reply

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