我开始玩别人的代码并遇到了一个有趣的实验。该程序将与 if 语句一起正常工作。但是我发现如果我将 if 语句更改为 while 循环,程序会运行,但我无法使用 X 按钮关闭程序,而是必须按下 Eclipse 终止按钮。我猜这是一个无限循环的迹象,还是 Java 不能一遍又一遍地重复绘制相同的图像的事实?
// if you want to draw graphics on the screen, use the paintComponent method
// it give you a graphic context to draw on
public void paintComponent(Graphics g){
super.paintComponent(g);
// when the player is still in the game
if(inGame){
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0)
g.drawImage(head, collisionX[z], collisionY[z], this);
else g.drawImage(tail, collisionX[z], collisionY[z], this);
}
Toolkit.getDefaultToolkit().sync();
// dispose graphics and redraw new one
g.dispose();
}
else gameOver(g);
}