' Get X, Y Coordinate at Mouse Clicked Location in Java Applet or Frame | Infolet

Get X, Y Coordinate at Mouse Clicked Location in Java Applet or Frame



Get Mouse Clicked Location in Java frame applet

We can capture any mouse clicked location or position on a java applet or frame. Here Mouse Adapter class used to implement mouse click event.

At the time of mouse click, variable x will get X coordinate an y will get Y coordinate or mouse click 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.drawLine(x,y,x,y);
    g.drawString(x + ","+ y, 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.drawLine(x,y,x,y);
    g.drawString(x + ","+ y, 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:

Get Mouse Clicked Location in Java frame applet

[Learn here how to make and run a java applet program]



Responses

0 Respones to "Get X, Y Coordinate at Mouse Clicked Location in Java Applet or Frame"

Post a Comment

 

Free Updates

Enter your email address:

Delivered by FeedBurner

Learn C

About Author

Author of infolet.org Muhammed Aslam PK, He is a MCA(Master of Computer Applications) student. See More here
Contact Us
Return to top of page Copyright © 2010 | Infolet.org Google Converted into Blogger Template by HackTutors