我有两个类,DrawSnakeGamePanel和Maze。我正试图在DrawSnakeGamePanel类的Maze类中调用一个方法。我想我已经启动了Maze类,但每次它都会触发一个NullPointerError。我不明白它指的是什么null。可能是一些很明显的东西,但我就是不明白。谢谢你的帮助。
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)
您没有为maze赋值。你需要这样做(数字是任意的):
private Maze maze = new Maze(3, 3 , 5);