Need a good way to pause between programmatic GUI updates so user can see what occurred before next action

36 Views Asked by At

I've been trying to code a simple graphical Yahtzee where, once it is the computer's turn, the user can see each of up to three CPU dice rolls for a few seconds before the next is displayed. But everything I've tried - Swing timer with ActionListener, Thread.sleep(), invokeAndWait, long while loops - essentially skips the first two validate/repaints, so the user never sees the first two rolls. I've read you shouldn't pause within the EDT, but I can't see how to avoid this, since the flow is: userScoreBtn clicked -> GUI update #1 [pause] -> GUI update #2 [pause] -> GUI update #3.

I'm working with a Java Swing JFrame.

// tried stuff like...
    Timer timer = new Timer(3000, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e {
        // roll code
    contentPane.validate();
    contentPane.repaint();
    }
});
timer.setRepeats(false);
timer.start();

// works once, but not 3X like I want`
1

There are 1 best solutions below

0
VGR On

You will need to use a variable to keep track of your animation’s state. For example:

Timer timer = new Timer(1000, new ActionListener() {
    private int step;

    @Override
    public void actionPerformed(ActionEvent e) {
        // roll code
        switch (++step) {
            case 1:
                // Show first roll state

                break;
            case 2:
                // Show second roll state

                break;
            case 3:
                // Show third roll state

                ((Timer) e.getSource()).stop();
                break;
            default:
                break;
        }

        contentPane.validate();
        contentPane.repaint();
    }
});
timer.setRepeats(true);
timer.start();

(It is not actually necessary to call setRepeats(true), since Timers repeat by default, but I have included it to emphasize that the timer needs to repeat for each frame of animation.)

You cannot use a loop to perform your animation. Execution of a GUI application is controlled by the system, not by the programmer.