A Name A Name - 6 months ago 20
Java Question

Changing icon every 200 milliseconds

I´m trying to change the icon on a JLabel every 200 milliseconds to simulate rolling a dice and I´ve been searching online and I can´t figure out how to set a Timer so I can run the method.
This is the method

public void dice(){
int whichOne=(int)(Math.random()*6+1);
if(whichOne==1){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice1.png")));}
else if(whichOne==2){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice2.png")));}
else if(whichOne==3){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice3.png")));}
else if(whichOne==4){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice4.png")));}
else if(whichOne==5){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice5.png")));}
else if(whichOne==6){jLabel12.setIcon(new ImageIcon(getClass().getResource("/spanish/dice6.png")));}
}


And this is how I´m currently calling the method

for(int i=0;i<9;i++){
dice();
}


Thanks for the help.

Answer

Here's one solution on how to call dice using Timer and TimerTask:

import java.util.*;

...

private void dieCaller() {
    TimerTask task = new TimerTask() {
        int numRolls = 0;

        @Override
        public void run() {
            if (numRolls < 9) {
                dice();
                numRolls++;
            }
            else {
                cancel();
            }
        }
    };

    Timer timer = new Timer("Die Roller");
    timer.scheduleAtFixedRate(task, 0, 200);
}

...

One other problem I have: don't load those ImageIcons everytime. Load them once and save like an array or something to refer to them later.