0
votes

I'm currently programming a video game. I'm using Util.Timer to keep track of multiple features of the game, but one of my issues is trying to change between background images. I'm trying to have the JPanel update to a new image every second, but so far no luck. I've used a JLabel to display the image inside the JPanel. I also make a call to displayFrame() after a second has passed. So now my question is how would I be able to update my JPanel every second with a new image? Here's my code:

public static void displayFrame(){
    panel_1.setBounds(10, 11, 519, 614);
    ImageIcon image = changeFrame();
    JLabel label = new JLabel("", image, JLabel.CENTER);
    panel_1.add(label, BorderLayout.CENTER);
    frame.getContentPane().add(panel_1);
}

public static ImageIcon changeFrame(){
    if(frameCounter == 9){
        frameCounter = 1;
    }
    if(frameCounter == 1){
        frameCounter = 2;
        return new ImageIcon("Capture.PNG");
    }
    if(frameCounter == 2){
        frameCounter = 3;
        return new ImageIcon("Capture2.PNG");
    }
    if(frameCounter == 3){
        frameCounter = 4;
        return new ImageIcon("Capture3.PNG");
    }
    if(frameCounter == 4){
        frameCounter = 5;
        return new ImageIcon("Capture4.PNG");
    }
    if(frameCounter == 5){
        frameCounter = 6;
        return new ImageIcon("Capture5.PNG");
    }
    if(frameCounter == 6){
        frameCounter = 7;
        return new ImageIcon("Capture6.PNG");
    }
    if(frameCounter == 7){
        frameCounter = 8;
        return new ImageIcon("Capture7.PNG");
    }
    if(frameCounter == 8){
        frameCounter = 9;
        return new ImageIcon("Capture8.PNG");
    }
    if(frameCounter == 9){
        frameCounter = 1;
        return new ImageIcon("Capture9.PNG");
    }
    return new ImageIcon("Capture.PNG");
    }
1

1 Answers

1
votes

I'm using Util.Timer

Don't use Util.Timer. You should be using a Swing Timer to make sure all updates to the GUI are done on the Event Dispatch Thread.

Then when the Timer fires you invoke the setIcon(...) method on your label to change the actual Icon.

Don't use multiple "if statements" to control which image is displayed. What if you want to have 100 images that would be a lot of code to type. Instead, I would store all your Images in an ArrayList. Then you just use the get(...) method of the ArrayList to get the image you want to display using your "frameCounter" variable. Then you update the counter for the next time the Timer fires.

Also, don't use static methods in your class. I suggest you read the Swing tutorial. The examples posted there show you how to better structure the code in your classes.