Implement Mouse Adapter Class java frame applet

Instead of implementing from MouseListener interface, we can use Mouse Adapter class. 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.

Program code 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.infolet.org",x,y);
 }
public class mymouselistener extends MouseAdapter
 {
  public void mouseClicked(MouseEvent e)
  {
  x = e.getX();
  y = e.getY();
  repaint();
  }
 }
}

Program code 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.infolet.org",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:

Implement Mouse Adapter Class java frame applet




No comments:

Post a Comment