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






6 comments:
  1. Swapfiets ging in één klap van 150 fietsen naar 1100.

    ReplyDelete
  2. Good site you have got here.. It's difficult to find high-quality writing like yours these days.
    I really appreciate people like you! Take care!!

    ReplyDelete
  3. This piece of writing gives clear idea for the new visitors of blogging, that
    in fact how to do blogging and site-building.

    ReplyDelete
  4. Good way of describing, and good article to obtain facts on the topic of my presentation subject, which i am going to convey in academy.

    ReplyDelete
  5. I'm pretty pleased to find this page. I need to to thank you for your time for
    this fantastic read!! I definitely enjoyed every
    bit of it and I have you saved to fav to look at new stuff on your
    website.

    ReplyDelete
  6. I always spent my half an hour to read this weblog's articles all the time along with a mug
    of coffee.

    ReplyDelete

Your Support Is Our Motivation