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
import java.awt.*;
import java.awt.event.*;

public class FrameMMLDemo extends Frame implements MouseMotionListener  
{                      
  TextField tf;
  public FrameMMLDemo()
  {
    add(tf = new TextField(), "South");
    tf.setFont(new Font("Monospaced", Font.BOLD, 18));

    addMouseMotionListener(this);
    setFocusable(true);               // cursor focus will be in frame

    setSize(300,300);
    setVisible(true);
  }                    
                                      // 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[])
  {
    new FrameMMLDemo();
  }                                    
}                                   

MouseEvent MouseMotionListener Example
Output screenshot on MouseEvent MouseMotionListener Example

addMouseMotionListener(this);

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

setFocusable(true);

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 Comment

Your email address will not be published.