<分区>
所以我创建了一个小贪吃蛇游戏。 在我的构造函数中,我调用了“CreateSnake”函数,它使用 JButtons 创建了一个 Snake。
private void createSnake()
{
snakeButtonx[0] = 100; //Sets the starter position of the snake
snakeButtony[0] = 150;
JButton tempButton; //temporary Button for adding button to the Snake
// Initially the snake has length of 5
for (int i = 0; i < sizeSnake; i++)
{
snakeButton[i] = new JButton("" + i);
snakeButton[i].setEnabled(false); // Disable the buttons so you cant click it
tempButton = snakeButton[i];
Surface.addSnake(tempButton, i);
snakeButton[i].setBounds(snakeButtonx[i], snakeButtony[i], 10, 10);
snakeButtonx[i + 1] = snakeButtonx[i] - 10;
snakeButtony[i + 1] = snakeButtony[i];
}
}
然后我有一个移动函数,通过线程每 100 毫秒调用一次
@SuppressWarnings("deprecation")
private void move()
{
snakeButtonx[0] += directionx; //Set the position of the head of the snake
snakeButtony[0] += directiony;
for (int i = 0; i < sizeSnake; i++)
{
snakeButtonPos[i] = snakeButton[i].getLocation(); //Fills the snakeButtonPos integer with the positions of every Button
}
snakeButton[0].setBounds(snakeButtonx[0], snakeButtony[0], 10, 10);
for (int i = 1; i < sizeSnake; i++)
{
snakeButton[i].setLocation(snakeButtonPos[i - 1]);
}
show();
}
所以。到这里,它工作正常。但是每当我想将第六个 JButton 添加到我的 JButton 数组时,我的移动方法中就会出现空指针异常。
private void Grow()
{
JButton tempButton = new JButton();
int newIndex = sizeSnake + 1;
// Add the new Button to the Button Array
snakeButton[newIndex] = new JButton();
snakeButton[newIndex].setEnabled(false);
tempButton = snakeButton[newIndex];
Surface.addSnake(tempButton, newIndex);
// Position is irrelevant, cause the position will be fixed at the next call of move()
snakeButton[newIndex].setBounds(200, 300, 10, 10);
sizeSnake = sizeSnake + 1;
}
第六个 JButton 在 Jbutton 数组中,而我在我的 Grow()
函数中。但是在下一次调用 move()
时,不再有索引为 6 的 JButton。
为什么会出现 NullPointerException?哪里错了?
编辑:错误发生在我的 move() 函数的第六个循环之后的这一行:snakeButtonPos[i] = snakeButton[i].getLocation();
确切的异常(exception):
Exception in thread "Thread-2" java.lang.NullPointerException
at Snake.move(Snake.java:92)
at Snake.run(Snake.java:217)
at java.lang.Thread.run(Unknown Source)
EDIT2:我在我的线程中调用移动和增长
@Override
public void run() {
while (true)
{
CheckPosition(); //CheckPosition includes Grow() if the snake intersects with an object
move();
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
}