强制Java刷新Java Swing GUI [英] Forcing Java to refresh the Java Swing GUI

查看:287
本文介绍了强制Java刷新Java Swing GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编码两台计算机在Reversi中相互播放,但是当它们相互播放时.游戏结束后,棋盘才会更新.

Ive coded two Computers to play each other in Reversi, however when they play each other. The board only updates after the game has finished.

从一些谷歌搜索中,我知道它可以做一些AWT事件线程,但是我仍然不知道如何强制JFrame刷新.

From some googling around I know its has something to do the AWT Event Thread, but I still have no idea how to force the JFrame to refresh.

我的函数通过更改图标然后调用revalidate和repaint来工作. 任何指针都很棒.

My function works by changing the icons and then calling revalidate and repaint. Any pointers would be wonderful.

推荐答案

如果从actionPerformed()开始AI游戏,则该游戏将在EDT线程中执行.您应该通过启动新的Thread将逻辑(和sleep()的内容移出EDT线程之外),以允许Swing正确地重新绘制UI并将更新发布到UI,如下所示:

If you start your AI game from an actionPerformed(), it is executed in EDT thread. You should move your logic (and your sleep()'s outside of EDT thread by starting a new Thread to allow Swing to repaint UI properly and post updates to UI as following:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        myUI.update();  // repaint(), etc. according to changed states
    }
});

还考虑使用javax.swing.SwingWorkerjavax.swing.Timer并查看 查看全文

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