访问另一个类时的AWT-Exception NullPointer

时间:2015-04-09 18:47:05

标签: java graphics

我有两个类,DrawSnakeGamePanel和Maze。我试图在我的DrawSnakeGamePanel类中调用我的Maze类中的方法。我想我启动了Maze类,但每次触发NullPointerError。我不明白它所指的是什么。可能是一些非常明显的东西,但我只是没有得到它。谢谢你的帮助。

public class DrawSnakeGamePanel extends JPanel {

private Snake snake;
private Kibble kibble;
private Score score;
private Maze maze;

DrawSnakeGamePanel(Snake s, Kibble k, Score sc){
    this.snake = s;
    this.kibble = k;
    this.score = sc;

public void paintComponent(Graphics g) {
    super.paintComponent(g);       

    switch (gameStage) {

    case 2 : {
        displayGame(g);  //exception here
        break;

}

private void displayGame(Graphics g) {
    displayGameGrid(g);
    displaySnake(g);
    displayKibble(g);
    maze.displayMaze(g);  //breaks here
  }
}

public class Maze extends JPanel {

int XnumOfSquares = (501 / 30);
int YnumOfSquares = (501/30);
int squareSize = 30;

public Maze(int maxX, int maxY, int squareSize){
    this.XnumOfSquares = maxX;
    this.YnumOfSquares = maxY;
    this.squareSize = squareSize;
}

public void displayMaze(Graphics g){
    g.fillRect(30,30,squareSize,squareSize);
    g.fillRect(30,60,squareSize,squareSize);
    g.fillRect(30,90,squareSize,squareSize);

}
}

错误堆栈:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.Marty.DrawSnakeGamePanel.displayGame(DrawSnakeGamePanel.java:118)
at com.Marty.DrawSnakeGamePanel.paintComponent(DrawSnakeGamePanel.java:66)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5222)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1572)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1495)
at javax.swing.RepaintManager.paint(RepaintManager.java:1265)
at javax.swing.JComponent._paintImmediately(JComponent.java:5170)
at javax.swing.JComponent.paintImmediately(JComponent.java:4981)
at javax.swing.RepaintManager$4.run(RepaintManager.java:824)
at javax.swing.RepaintManager$4.run(RepaintManager.java:807)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:807)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:782)

1 个答案:

答案 0 :(得分:1)

您没有为迷宫分配值。你需要这样做(数字是任意的):

private Maze maze = new Maze(3, 3 , 5);