Thread.sleep inside of for loop to update ImageView

31 Views Asked by At

I have a JavaFX program where I have 2 dice that I want to be able to click on, have them "animate" and then stop. To do this, I have a for loop that will run 15 times and each iteration will change the image view of each of the 2 dice to a different die face and will create a flickering effect, making it look like the dice are rolling. At the end of each iteration I am using Thread.sleep() to pause very briefly. The time does not need to be precise or accurate so I didn't feel like doing it this way would be much of a problem. Unfortunately, the dice do not animate and instead just pause for a moment before settling on the 15th iteration. Seen a couple of solutions on Swing but hoping to get one for JavaFX. Thanks!!

Image[] diceImages = {
            new Image("dOne.png"),
            new Image("dTwo.png"),
            new Image("dThree.png"),
            new Image("dFour.png"),
            new Image("dFive.png"),
            new Image("dSixFixed.png")
    };

public void rollDice() throws InterruptedException {

        Random random = new Random();
        int d1CurrentIndex = 5;
        int d2CurrentIndex = 5;
        int numberOfDieBounces = 15;

        for(int i = 0; i < numberOfDieBounces; i++){

            boolean newNumberIsSameAsOld = true;
            while(newNumberIsSameAsOld){
                int randomIndexD1 = random.nextInt(6);

                if(randomIndexD1 != d1CurrentIndex){
                    d1CurrentIndex = randomIndexD1;
                    newNumberIsSameAsOld = false;
                }
            }

            newNumberIsSameAsOld = true;
            while(newNumberIsSameAsOld){
                int randomIndexD2 = random.nextInt(6);

                if(randomIndexD2 != d2CurrentIndex){
                    d2CurrentIndex = randomIndexD2;
                    newNumberIsSameAsOld = false;
                }
            }

            Thread.sleep(100);
            firstDie_img.setImage(diceImages[d1CurrentIndex]);
            secondDie_img.setImage(diceImages[d2CurrentIndex]);
        }

        int totalSpaces = d1CurrentIndex + 1 + d2CurrentIndex + 1;
        moveToSpace(totalSpaces);
    }
0

There are 0 best solutions below