Handling MouseEvent with MouseMotionListener Example

Handling MouseEvent with MouseMotionListener Example

There is no MouseMotionEvent in java. The same MouseEvent used in MouseListener is used in MouseMotionListener also. All the abstract methods of both the interfaces takes MouseEvent as parameter.

Two types of events can be generated with by mouse button when the mouse is in motion. One is just moving the mouse on a component and the other when the mouse is being dragged (moving the mouse while mouse button is being pressed). These two types of actions can be handled by MouseMotionListener.

The two types of events, while mouse is in motion, are represented by two abstract methods of MouseMotionListener. Following table illustrates.

Action Name Represented by abstract method of MouseMotionListener
Mouse is moving over a component void mouseMoved(MouseEvent)
Mouse is dragged over a component (like mouse dragging in MS-Word while selecting some text) void mouseDragged(MouseEvent)

This example illustrates how to handle the events when the mouse is in motion using MouseMotionListener by overriding the above 2 abstract methods. In this code, the mouse action is displayed in a text field.

MouseEvent MouseMotionListener Example

MouseEvent MouseMotionListener Example
Output screenshot on MouseEvent MouseMotionListener Example


This method, defined in Frame class, registers the frame with the MouseMotionListener. When registered, the mouse actions on the frame are handled by MouseMotionListener.


If this statement does not exist, by cursor is focussed in text field implicitly. This statement makes the cursor focus in the frame.

Leave a Reply

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