// ShowPoint.java: Show point coordinates when user clicks mouse.
// You can execute this as program (java ShowPoint) or applet
// (appletviewer ShowPoint.html or double-click on icon).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ShowPoint extends JApplet
implements MouseListener
{
// Point is a Java object for representing points in a plane.
// p.x and p.y are the x and y coordinates.
private Point p = new Point(0, 0);
public void init()
{
// Register ShowPoint object (this) as listener for mouse events.
addMouseListener(this);
}
// Main method
public static void main(String[] args)
{
// Create frame with title.
JFrame frame = new JFrame("Click to Show Point Coordinates");
// Create instance of ShowPoint.
ShowPoint applet = new ShowPoint();
// Add applet instance to frame.
frame.getContentPane().add(applet, BorderLayout.CENTER);
// Add window listener interface using anonymous class.
// Use adapter class so it implements all seven methods.
frame.addWindowListener(new WindowAdapter()
{
// Quit application when quitting frame, else you must do CTRL-c.
public void windowClosing(WindowEvent event)
{
System.exit(0);
}
});
// Invoke init() and start().
applet.init();
applet.start();
frame.setSize(600, 300);
frame.setVisible(true);
}
// MouseListener has five listener methods (handlers). You must
// define all methods. You can avoid having to explicitly do
// this by using an adapter class. The MouseAdapter adapter
// class implements the MouseListener interface.
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
// Listener reacts to click, right-click, or double-click.
// Point p holds mouse pointer location.
public void mouseClicked(MouseEvent e)
{
p.x = e.getX();
p.y = e.getY();
repaint();
}
// Draw small square around point followed by coordinates.
public void paint(Graphics g)
{
g.drawRect(--p.x, --p.y, 2, 2);
g.drawString("("+p.x+", "+p.y+")", p.x, p.y);
}
}