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`
You will need to use a variable to keep track of your animation’s state. For example:
(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.