I’m doing a simple game in Java.
I have one Class named “Drawer” to repaint every 50 miliseconds the images that I save in BufferedImages’ s array.
I have a method to convert the player in a huge player in the Player Class and the code is:
public void playerEvolution() {
for (int i = 0; i < 5; i++) {
this.setImageIndex(15);
try {
Thread.sleep(500);
this.setImageIndex(17);
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.isHuge();
}
I want alternate 2 images every 0.5 seconds but in the GamePanel doesn’t alternated any images and only appear the final image when spend 2.5 seconds (0.5 * 5 loops).
Any ideas??
If this is a Swing application (you don’t say), use a javax.swing.Timer or Swing Timer. Never call
Thread.sleep(...)on the main Swing event thread, known as the Event Dispatch Thread or EDT. Have an int count variable in your Timer’s ActionListener which is incremented each timeactionPerformed(...)is called, and stop the Timer if the count > to a max count (here 5 * 2 since you’re swapping back and forth).e.g.,