I started playing with someone's else code and came across an interesting experiment. The program will work fine with the if statement. But I found out if I change the if statement into a while loop, the program runs but I could not close the program with the X button instead I had to press Eclipse terminate button. I am guessing this is a sign of an infinite loop or is it the fact that Java cannot repeatedly draw the same images over and over again?
// 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);
}
Changing this line into a while statement
if (inGame) {
will not allow the variable to be reset to false, resulting in the infinite loop. Having while loops or any resource-heavy calls in paintComponent is a bad idea in general. Swing has concurrency mechanisms to deal with these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With