|
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import javax.swing.*;
public class MousePoints extends JPanel
{
Point start;
Point end;
JLabel label;
NumberFormat nf;
int lastPoint;
final int START_POINT = 0;
final int END_POINT = 1;
public MousePoints()
{
start = new Point(-2,-2);
end = new Point(-2,-2);
nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
lastPoint = END_POINT;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawLine(start.x, start.y, end.x, end.y);
g2.setPaint(Color.red);
g2.fillRect(start.x-2, start.y-2, 4, 4);
g2.fillRect(end.x-2, end.y-2, 4, 4);
}
public void setPoint(Point p)
{
if(lastPoint == START_POINT)
{
end = p;
lastPoint = END_POINT;
}
else
{
if(end.x == -2) // for the first time
end = p;
start = p;
lastPoint = START_POINT;
}
setDistance();
repaint();
}
private void setDistance()
{
double distance = start.distance(end);
label.setText(nf.format(distance));
}
private JLabel getLabel()
{
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
Dimension d = label.getPreferredSize();
d.height = 35;
label.setPreferredSize(d);
return label;
}
public static void main(String[] args)
{
MousePoints mp = new MousePoints();
PointPlacer placer = new PointPlacer(mp);
mp.addMouseListener(placer);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(mp);
f.getContentPane().add(mp.getLabel(), "South");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class PointPlacer extends MouseAdapter
{
MousePoints mousePoints;
public PointPlacer(MousePoints mp)
{
mousePoints = mp;
}
public void mousePressed(MouseEvent e)
{
mousePoints.setPoint(e.getPoint());
}
}
This coding from crwood..
Can change it to javascripts?
|
|
|
|
|
|
|
|