Reputation: 2998
I'm creating a simple board game in Java using Swing with an AI that is supposed to take its turn after the user takes their turn. I want to "pause" the game for about 3 seconds before I allow the AI to take its turn so that the user can see the results of their move. Calling Thread.sleep(3000) also pauses the animations I created using the Trident Animation Library. After the end of the three seconds, the spaces just turn to the color they're supposed to be, no animation done at all.
If anyone can offer any advice, please do. I know I can always add a "Continue" button that the user can press before the AI takes its turn, but I'd like to avoid that step.
Edit: Here's my Single Player panel. It extends GamePanel which is just an abstract class which has a method to update the GUI based on the current board. It also extends JPanel. I think I'm just a little unclear as to where/how to implement the timer to do what I want it to do, whether it's in this class or another.
Upvotes: 1
Views: 217
Reputation: 3580
Assuming you are running the AI code in a separate thread anyway (you wouldn't want to lock up the UI while running that complicated AI stuff, right?), you want the pause to happen in the AI thread, not the UI thread. Add your Thread.sleep() there.
If you are not currently using a separate Thread for the AI, and this is starting to sound less 'simple' than you intended, have a look at using Futures and Callables, a nice way of preforming background operations and chaining events to occur when they complete.
Upvotes: 1
Reputation: 285403
Never call Thread.sleep()
on the Swing event thread or EDT as this will tie up this thread preventing Swing from doing any graphics or interacting with the user. Use a Swing Timer instead. e.g.,
int delay = 3000;
new Timer(delay , new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// tell AI to do its thing
((Timer)e.getSource()).stop();
}
}).start();
For more on the Swing Event Dispatch Thread or EDT, please read: Concurrency in Swing
Upvotes: 4