在创建类的新对象后获取NPE



我正在尝试使用挥杆进行"游戏",但遇到了一个无法解决的问题。这可能是一件简单而明显的事情,但我仍然不明白。这是我的一段代码:

public class LevelOne {
private static Crate[] crates = new Crate[3];        
public LevelOne(){
    crates[0].setX(200);
    crates[0].setY(200);
    crates[1].setX(280);
    crates[1].setY(40);
    crates[2].setX(440);
    crates[2].setY(40);
}
//more code here
}

我试图创建LevelOne类的对象,以使我的crates变量活起来。(这是一种方法吗?)。

public static void main(String[] args) {
    LevelOne l = new LevelOne();
    JFrame frame = new JFrame("blabla");
    Board board = new Board();
    frame.add(board);
    frame.setSize(805, 830);
    frame.setVisible(true);
    frame.setFocusable(false);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(3);
    frame.setLocation(400, 200);
    board.requestFocus(true);
}

它在线上给了我NPE

LevelOne l = new LevelOne();

正如我所说,这只是一个小项目,但我认为这可能会解决整个问题。我用这个Crate[]板条箱在我的板上油漆部件,检查碰撞和其他东西。在没有创建LevelOne类的对象的情况下,我在绘制它们时仍然会得到NPE。有什么建议、想法、解决方案吗?

您忘记初始化板条箱中的元素:

private static Crate[] crates = new Crate[3];        
public LevelOne(){
    crates[0] = new Crate(); // <= add this
    crates[0].setX(200);
    crates[0].setY(200);
    // same for other elements

您必须将Crate对象传播到crates数组中。您得到NullPointerException,因为crates数组中没有任何对Carte的引用。请执行以下操作。

private static Crate[] crates = new Crate[3];        
public LevelOne(){
    for(int i = 0; i < crates.length; i++)
        crates[i] = new Crate();
    crates[0].setX(200);
    crates[0].setY(200);
    crates[1].setX(280);
    crates[1].setY(40);
    crates[2].setX(440);
    crates[2].setY(40);
}

最新更新