我试图用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)
}
}
答案 0 :(得分:0)
问题在于:
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 + ".");
}
...
}