MouseMotionListener Example

MouseMotionListener Example


The events generated by the mouse come under low-level events. We have seen previously how to handle the events of a mouse when the mouse is stable with MouseListener. Let us handle the events when the mouse is in motion. Two types of actions can be generated when the mouse is in motion – just moving the mouse and while dragging (moving the mouse while mouse the key is being pressed). These two actions are handled by the two abstract methods of MouseMotionListener – mouseMoved() and mouseDragged(); both take MouseEvent as parameter.

Two programs are given, the first one being simple like the one of MouseListener and the second one is a bigger one which implements both MouseListener and MouseMotionListener.

MouseMotionListener Example changing the background of the frame as per the action.


Output screen of MouseMotionListener Example

Following second program on MouseMotionListener Example implements both the mouse listeners. Where the action takes place with the mouse in the frame window, in the same spot one disc (filled oval) is displayed along with coordinates and type of action occurred.

MouseMotionListener Example

Output screen of MouseMotionListener Example

x = e.getX();
y = e.getY();

getX() and getY() methods of MouseEvent class return the x and y coordinates where the mouse action taken place. With fillOval() method of Graphics class a disc is drawn on the frame and with drawString() method , two strings are drawn of x and y coordinates and the type of action taken. Also learn repaint() method.

Leave a Reply

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