Implement mouse listener java name at mouse click

This is a simple java applet program to implement mouse events. This program implemented ‘MouseListner’ interface for getting mouse events. So you need to overload all mouse events such as ‘mouseEntered, mousePressed, mouseReleased, mouseClicked, and mouseReleased’. Here Infolet used only ‘mouseClicked’ event for example. Instead of implementing from MouseListener interface, you can use MouseAdapter class to avoid typing all mouse events.
Here this program will show your name at your mouse clicked location. [Learn here how to make and run a java applet program]. You can do this same program using Frame by edit and adding main.
 Program code:


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

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

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

 public void init()
 {

 }
 public void start()
 {
 addMouseListener(this);
 }
 public void paint(Graphics g)
 {
    g.drawString("www.infolet.org", x,y);
 }
 public void mouseClicked(MouseEvent e)
 {
   x = e.getX();
   y = e.getY();
   repaint();
 }
 public void mousePressed(MouseEvent e)
 {

 }
 public void mouseReleased(MouseEvent e)
 {

 }
 public void mouseEntered(MouseEvent e)
 {

 }
 public void mouseExited(MouseEvent e)
 {

 }

}

Sample output:


Implement mouse listener java name at mouse click




No comments:

Post a Comment