MouseEvent MouseListener Example Applet


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

What mouse events and key events possible with frame are also possible with applet because frame and applet are containers (that can hold AWT components) derived from the same java.awt.Container class. Following is their hierarchy.

MouseListener Example

As usual every applet file should be accompanied by a HTML file.

Following two programs of MouseListener Example illustrate.

HTML file to run the applet



Java applet File Name: AppletMouseListener.java

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class AppletMouseListener extends Applet implements MouseListener
{
  String str="";
                       // init() in place of frame constructor
  public void init()
  {
    addMouseListener(this);
  }
                       // override all the 5 abstract methods of MouesListener
  public void mousePressed(MouseEvent e)
  {
    str = "You pressed mouse";
    repaint();
  }
  public void mouseReleased(MouseEvent e)
  {
    str = "You released mouse";
    repaint();
  }  
  public void mouseClicked(MouseEvent e)
  {
    str = "You clicked mouse";
    repaint();
  }  
  public void mouseEntered(MouseEvent e)
  {
    str = "Mouse entered frame";
    repaint();
  }  
  public void mouseExited(MouseEvent e)
  {
    str = "Mouse existed frame";
    repaint();
  }
                       // write paint() method to draw on applet window
  public void paint(Graphics g)
  {
    g.drawString(str, 75, 150); 
  }
}

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

public class AppletMouseListener extends Applet implements MouseListener

Observe, the applet implements MouseListener.

addMouseListener(this);

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

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

g.drawString(str, 75, 150);

The string str is drawn in applet window with Graphics class drawString() method at x coordinate of 75 and y coordinate of 150.


MouseListener Example
Output screen when mouse is clicked on applet window of MouseListener Example.

Leave a Comment

Your email address will not be published.