JFrame 在 thread.sleep() 之前没有更新 [英] JFrame not updating before thread.sleep()

查看:31
本文介绍了JFrame 在 thread.sleep() 之前没有更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 GUI 和 JFrames/JPanels 创建棋盘游戏,您可以在其中与计算机对战.我有一个名为 showPieces() 的方法,它通过更改按钮阵列(以网格格式布局)上的图像图标来更新板 GUI.更新图标后,revalidate()repaint() 方法来更新 GUI.showPieces() 方法有一个参数,每次调用时都需要传递给它.

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.

我遇到的主要问题是我希望人类移动,更新 GUI,等待 1 秒,计算机移动然后循环直到有人获胜.我的基本代码如下:

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

这会导致当人类玩家移动时,GUI 会冻结一秒钟,然后在延迟后,两个移动同时进行.

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.

我希望它有道理,但我是 Java 的新手,可能需要更多地研究线程,因为我对它的理解不够好.

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.

推荐答案

Thread.sleep() 在事件调度线程上完成,它将锁定 GUI.

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

这篇关于JFrame 在 thread.sleep() 之前没有更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆