JFrame not updating before thread.sleep()

匆匆过客 提交于 2019-11-26 18:40:14

问题


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.


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/30007369/jframe-not-updating-before-thread-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!