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
public class FrameMMLDemo extends Frame implements MouseMotionListener
add(tf = new TextField(), "South");
tf.setFont(new Font("Monospaced", Font.BOLD, 18));
setFocusable(true); // cursor focus will be in frame
// override the 2 abstract methods of MouseMotionListener
public void mouseMoved(MouseEvent e)
tf.setText("Mouse moving is going on");
public void mouseDragged(MouseEvent e)
tf.setText("Mouse dragging is going on");
public static void main(String snrao)
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.