我正在尝试用Java Point计算2个点之间的距离,它运行良好,直到我说例如:double point1x=point1.getX();。因为当我这样做的时候,我会收到一个错误。有人能帮我找出代码中的问题吗?
public class ClickAndCalc extends JFrame implements MouseListener {
public ClickAndCalc() throws IOException{
addMouseListener(this);
}
public static void Window() throws IOException {
String path = "kaakfoto.jpg"; //imported image
File file = new File(path);
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
JLabel label = new JLabel(new ImageIcon(image)); //add the image to the JLabel
System.out.println("height: " + height); //print out the height and width of the image
System.out.println("width: " + width);
ClickAndCalc frame = new ClickAndCalc(); //make a new frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.setSize(width+3, height+26); //set the size of the frame the same as the size of the image
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
int i=0;
Point p1, p2, p3;
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) { //when clicked add point for 3 times
if(i==0) {
p1 = e.getPoint();
System.out.println("coordinates Point1: X=" + p1.getX() + ". Y=" + p1.getY());
}
else if(i==1) {
p2 = e.getPoint();
System.out.println("coordinates Point2: X=" + p2.getX() + ". Y=" + p2.getY());
}
else if(i==2) {
p3 = e.getPoint();
System.out.println("coordinates Point3: X=" + p3.getX() + ". Y=" + p3.getY());
}
i++;
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
//down here is some mistake i can't find
double distanceAB(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}
double x1 = p1.getX(), //convert getX and getY to doubles
y1 = p1.getY(),
x2 = p2.getX(),
y2 = p2.getY(),
distanceAB;{
distanceAB = distanceAB(x1, y1, x2, y2); //calculate the distance between point A and B
System.out.println("the distance between the points AB is " + distanceAB + ".");
}
public static void main(String[] args) throws IOException {
Window(); //add the window (frame, label, image)
}
}
问题就在这里:
double x1 = p1.getX(), //convert getX and getY to doubles
y1 = p1.getY(),
x2 = p2.getX(),
y2 = p2.getY(),
distanceAB;
您正在定义类ClickAndCalc
的成员变量。这些成员变量是在创建类的新实例时初始化的,也就是调用p1.getX()
、p1.getY()
、p2.getX()
和p2.getY()
的时刻。然而,在这一点上,p1
和p2
是null
,所以您得到了一个NullPointerException
。
只有在确定坐标后,也就是说,在框架上单击两次后,才能调用计算p1
和p2
之间的距离。最简单的解决方案是将代码移动到mousePressed
方法:
public void mousePressed(MouseEvent e) { //when clicked add point for 3 times
if (i==0) {
...
}
else if (i==1) {
p2 = e.getPoint();
System.out.println("coordinates Point2: X=" + p2.getX() + ". Y=" + p2.getY());
double x1 = p1.getX();
double y1 = p1.getY();
double x2 = p2.getX();
double y2 = p2.getY();
double distanceAB = distanceAB(x1, y1, x2, y2);
System.out.println("the distance between the points AB is " + distanceAB + ".");
}
...
}