Nic*_*las 2 java graphics loops infinite paintcomponent
我开始玩别人的其他代码并遇到了一个有趣的实验.该程序将与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);
}
Run Code Online (Sandbox Code Playgroud)
将此行更改为while语句
if (inGame) {
Run Code Online (Sandbox Code Playgroud)
不允许将变量重置为false,从而导致无限循环.paintComponent一般而言,while循环或任何资源繁重的调用都是一个坏主意.Swing具有并发机制来处理这些问题.