Mouse as an input device can generate major 8 events. Among those 8 events below 2 of them can be handled by MouseMotionListener, 1 is handled by MouseWheelListener and rest can be handled using MouseListener.

MouseMotionListener Interface

As per the event delegation model we are going to implement this interface in our class. MouseMotionListener consists of 2 methods which are as below.

  1. public void mouseMoved(MouseEvent e)
  2. public void mouseDragged(MouseEvent e)

To add MouseMotionListener on whole applet area the syntax will be: this.addMouseMotionListener(this);
In above line 1st “this” stands for current class on which we would like to handle the Mouse related events. And 2nd “this” is the object of current class which has implemented MouseMotionListener and defined all the methods. For further reference you can refer my article on Event Handling Methodologies.

To manually invoke paint(Graphics) method: we can call repaint(). This will internally create object of java.awt.Graphics and call paint(Graphics) internally.

Program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AppletMouseMotionEvents extends Applet implements MouseMotionListener
{
	int mouseX = 0, mouseY = 0; 
	String msg = "";
	public void init() 
	{
		this.addMouseMotionListener(this);
	}
	public void mouseMoved(MouseEvent me) 
	{
		mouseX = me.getX();
		mouseY = me.getY();
		msg = "Moved";
		repaint();
	}
	public void mouseDragged(MouseEvent me) 
	{
		mouseX = me.getX();
		mouseY = me.getY();
		msg = "Dragged";
		repaint();
	}
	
	public void paint(Graphics g) 
	{
		g.drawString(msg+"("+mouseX+","+mouseY+")", mouseX, mouseY);
	}
}
/*
<applet code="AppletMouseMotionEvents" width="300" height="300"></applet>
*/