Question

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??

Was it helpful?

Solution

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 time actionPerformed(...) 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.,

public void playerEvolution() {
  int delay = 500; // ms
  javax.swing.Timer timer = new javax.swing.Timer(delay , new ActionListener() {
     private int count = 0;
     private int maxCount = 5;

     @Override
     public void actionPerformed(ActionEvent evt) {
        if (count < maxCount * 2) {
           count++;
           // check if count is even to decide 
           // which image to use, and then
           // do your image swapping here
        } else {
           ((javax.swing.Timer)evt.getSource()).stop();
        }
     }
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top