MouseListener MouseAdapter Applet


We know in Java, every listener interface that has got more than one abstract method comes with a corresponding adapter class. Usage of adapters classes in Java programming makes coding simple. Two programs (one as applet and the other as frame) are given to handle the events of mouse with MouseListener and MouseAdapter. To understand the concept, small action is done of changing the background of applet window. For a change, the java.awt.Frame is replaced by java.applet.Applet window.

Learn more on Applets – Applets Vs Applications
Learn more on Adapters – Java AWT Adapters
Learn frame closing with WindowAdapter.

I. MouseListener MouseAdapter Applet

First Program – Using MouseListener with Applet

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

public class Demo extends Applet implements MouseListener
{
  public void init()
  {
    addMouseListener(this);
  }
  	      // override all the five abstract methods of MouseListener
  public void mouseClicked(MouseEvent e) 
  {
    setBackground(Color.red);
  }
  public void mousePressed(MouseEvent e) {   }
  public void mouseReleased(MouseEvent e)  {  }
  public void mouseEntered(MouseEvent e) {   }
  public void mouseExited(MouseEvent e)  {  }
}

Also write a HTML program (Demo.html) to run the above applet.



appletveiwer screen with Demo.html

In the above code, the MouseListener forces to override all its five abstract methods, it being an interface, even though the code does not warrant. In the above code, only the method mouseClicked(MouseEvent e) is overridden and the other are given empty body. This is overcome in the next program using MouseAdapter.

II. MouseListener MouseAdapter Applet

Second Program – Using MouseAdapter with Frame

import java.awt.*;
import java.awt.event.*;

public class Demo extends Frame
{
  public Demo()
  {
    MyAdapter ma = new MyAdapter();
    addMouseListener(ma);

    setSize(300,300);
    setVisible(true);
  }
  public static void main(String args[])
  {
    new Demo();
  }
}

class MyAdapter extends MouseAdapter
{
  public void mouseClicked(MouseEvent e) 
  {
    System.out.println("You clicked the mouse");
  }
}
MouseListener MouseAdapter Applet
Output screen of MouseListener MouseAdapter Applet

MouseAdapter is an abstract class from java.awt.event package and cannot be extended to the main class (as Java does not support multiple inheritance). For this reason, a separate class MyAdapter is created and is used to extend MouseAdapter. This is the case with any Java adapter in GUI programming. The advantage of MosueAdapter is only one method, mouseClicked(), is overridden as we are interested only in this method to override.

Leave a Comment

Your email address will not be published.