我开始使用别人的else代码,发现了一个有趣的实验。该程序可以很好地与if语句配合使用。但我发现,如果我将if语句更改为while循环,程序会运行,但我不能使用X按钮关闭程序,而是必须按Eclipse terminate按钮。我猜这是一个无限循环的迹象,还是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);
}发布于 2013-01-01 07:16:57
如果希望UI保持响应,事件处理程序和重绘应该在合理的时间内完成。这意味着您根本不应该在paintComponent()中循环;相反,您必须从其他地方重复触发重新绘制,如动画计时器。
发布于 2013-01-01 07:11:52
将此行更改为while语句
if (inGame) {将不允许将变量重置为false,从而导致无限循环。一般来说,在paintComponent中使用while循环或任何占用大量资源的调用都不是一个好主意。Swing有concurrency mechanisms来处理这些问题。
发布于 2013-01-01 07:11:46
将if更改为while,即:
while(inGame){如果inGame为真,将永远循环,因为只有两种方法可以退出循环:
在循环内将
inGame设置为false break语句in the loop它们在代码中都找不到。
仅供参考,代码模式while(true)是创建无限循环的常用方法,这对于等待请求的web服务来说是必需的
https://stackoverflow.com/questions/14106688
复制相似问题