Blease
Blease

Reputation: 1420

JFrame not updating before thread.sleep()

I'm creating a board game using a GUI and JFrames/JPanels where you can play against the computer. I have a method called showPieces() which updates board GUI by changing the image icons on an array of buttons (which are laid out in a grid format). Once the icons have been updated the revalidate() and repaint() methods to update the GUI. The showPieces() method has a parameter that needs to be passed to it every time it is called.

The main issue I'm having is I want the human to make a move, update the GUI, wait 1 second, the computer makes it's move and then loop until someone wins. My basic code is the following:

do{
    human.makeMove();
    gui.showPieces(data);
    try {
        Thread.sleep(1000);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    computer.makeMove()
    gui.showPieces(data);
}while(playing);

This cause the issue where when the human player makes their move, the GUI will freeze for one second and then after the delay, both moves are made at the same time.

I hope it makes sense, but I'm a novice with Java and may have to look more into threading as I don't understand it well enough.

Upvotes: 0

Views: 3478

Answers (2)

MChaker
MChaker

Reputation: 2648

Thread.sleep() is done on the Event Dispatch Thread which will lock the GUI.

So If you need to wait for a specific amount of time, don't sleep in the event dispatch thread. Instead, use a timer.

 int delay = 1000; //milliseconds
  ActionListener taskPerformer = new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
          //...Perform a task...
      }
  };
  new Timer(delay, taskPerformer).start();

Upvotes: 7

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

As with most all similar Swing questions, you're putting your entire Swing GUI to sleep by calling Thread.sleep(...) on the GUI's event thread (the EDT or Event Dispatch Thread), and when during this period the GUI will not be able to update its images or interact with the user whatsoever. The solution here is not to use Thread.sleep(...) but rather to use a Swing Timer to cause your 1 second delay.

Swing Timer Tutorial.

Upvotes: 1

Related Questions