MouseMotionListener Example Applet

April 30, 2014 | AWT Events in Java

Note: Before going into this tutorial, it is advised to have better knowledge of Applet.

Applets are also capable to raise mouse and key events like with frame. Following program illustrates how to use MouseMotionListener with applet.

MouseMotionListener Example as Applet

HTML file to run the applet

Java applet File Name: AppletMouseMotionListener.java

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;

public class AppletMouseMotionListener extends Applet implements MouseMotionListener
{
  int status;
  public void init()
  {
    addMouseMotionListener(this);
  }
                               // override 2 methods of MouseMotionListener
  public void mouseMoved(MouseEvent e)
  {
    status = 0;
    repaint();
  }
  public void mouseDragged(MouseEvent e)
  {
    status = 1;
    repaint();
  }
                               // write paint() method to draw on applet window
  public void paint(Graphics g)
  {
    if(status == 0)            // rectangle is drawn when mouse is moving 
    {
      g.setColor(Color.blue);
      g.fillRect(50, 100, 150, 100);
      showStatus("Mouse is moving");
    }
    else if(status == 1)       // oval is drawn when mouse is dragged 
    {
      g.setColor(Color.red);
      g.fillOval(50, 100, 150, 100);
      showStatus("Mouse is dragging");
    }
  }
}

No main() method and no constructor, it is being an applet.

public class AppletMouseMotionListener extends Applet implements MouseMotionListener

Observe, the applet implements MouseMotionListener.

addMouseMotionListener(this);

Applet window is added with MouseMotionListener in init() method.

The paint() method should be called with repaint() only. Calling paint() directly raises compilation error. Why?

showStatus("Mouse is moving");

showStatus(String) defined in Applet class displays in the status bar of applet window. See the output screen.

MouseMotionListener Example Output screen of mouse events of MouseMotionListener Example