我最近遇到了一个困扰我的问题。我将 Point2D 对象的位置设置为另一个预先存在的 Point2D 对象。当我将预先存在的点分配给新点时,我得到一个空指针异常。为了更好地解释这一点,这里是我的代码和输出。输出清楚地表明第一个点已初始化,并且具有明显的空指针之前的值。有谁知道为什么会这样?
代码:
private Point2D position;
public Enemy(Map map, double speed) {
if (Panel.waypoints.size() < 1) {
Panel.waypoints.add(new Waypoint(0, 0));
}
System.out.println(Panel.waypoints.get(0).getPoint());
position.setLocation(Panel.waypoints.get(0).getPoint());//this line throws the NPE
System.out.println(position);
}
安慰:
Point2D.Double[331.0, 284.0]
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at towerdefencev2.Enemy.<init>(Enemy.java:36)
at towerdefencev2.Panel.mouseReleased(Panel.java:72)
at java.awt.Component.processMouseEvent(Component.java:6505)
谢谢,
缺口。
编辑:
航点类:
int x, y;
Point2D point;
public Waypoint(int x, int y) {
this.x = x;
this.y = y;
point = new Point2D.Double(x, y);
}
Point2D getPoint() {
return point;
}