Press "Enter" to skip to content

Java How to Use Mouse Adapter Class with Applet or Frame

Instead of implementing from MouseListener interface, we can use Mouse Adapter class with applet or frame. This method helps to avoid overloading of all mouse events such as Mouse Entered, Mouse Pressed, Mouse Release, Mouse Clicked, and Mouse Exited.

This is a simple java program to understand how to implement mouse adapter class. Here only ‘mouse clicked’ event had used. You can use any other events mentioned above.
Here, a name will display at the mouse clicked location. 

Mouse Adapter with Applet:

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

 /* <applet code = "mouseevent" width = 400 height = 200> </applet> */

public class mouseevent extends Applet
{
  int x=0;
  int y=0;

 public void init()
 {
   addMouseListener(new mymouselistener());
 }
 public void start()
 {

 }
 public void paint(Graphics g)
 {
   g.drawString("www.yourowncodes.com",x,y);
 }
public class mymouselistener extends MouseAdapter
 {
  public void mouseClicked(MouseEvent e)
  {
   x = e.getX();
   y = e.getY();
   repaint();
  }
 }
}

Mouse Adapter with Frame

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

public class mouseevent2 extends Frame
{
  int x=0;
  int y=0;

 public void init()
 {
   addMouseListener(new mymouselistener());
   addWindowListener(new MyWindowAdapter());
 }

 public void paint(Graphics g)
 {
   g.drawString("www.yourowncodes.com",x,y);
    /*int a = x;
   int b = y;
   g.drawLine(x,y,x,y);
   g.drawString(a + ","+ b, x,y);*/
 }
public class mymouselistener extends MouseAdapter
 {
  public void mouseClicked(MouseEvent e)
  {
   x = e.getX();
   y = e.getY();
   repaint();
  }
 }
 class MyWindowAdapter extends WindowAdapter
 {
public void windowClosing(WindowEvent we)
 {
System.exit(0);
 }
}
public static void main(String p[])
{
  mouseevent2 me2 = new mouseevent2();
  me2.setSize(250, 250);
  me2.setVisible(true);
  me2.init();
 }
}

Sample Output:

Java How to Use Mouse Adapter Class with Applet or Frame

Learn here how to get mouse clicked X, Y position with Applet.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *