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

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

问题描述

我正在使用GUI和JFrames / JPanel创建一个棋盘游戏,您可以在其中与计算机对战。我有一个名为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();

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

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