【问题标题】:Updating GUI gives a flickering effect更新 GUI 会产生闪烁效果
【发布时间】:2011-11-22 09:20:25
【问题描述】:

我目前有一个 JFrame,在它的内容窗格上,我以每秒 60 帧的速度从游戏循环中绘制图像。这很好用,但在右侧,我现在有更多 Swing 元素,我希望在选择内容窗格的某些部分时在这些元素上显示一些信息。该部分是静态 GUI,不使用游戏循环。

我是这样更新的:

public class InfoPanel extends JPanel implements Runnable {
    private String titelType = "type: ";
    private String type;
    private JLabel typeLabel;
    private ImageIcon icon;

    public void update() {
        if (this.icon != null)
            this.typeLabel.setIcon(this.icon);

        if(this.type != null || this.type != "")
            this.typeLabel.setText(this.titelType + this.type);
        else
            this.typeLabel.setText("");
    }

    public void run() {
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.update();
    }

(此方法仅在玩家实际移动时调用,因此只调用一次 - 不是每秒 60 次)

我注意到,当从游戏循环中调用此 update() 方法时,我会得到闪烁效果。我认为这是因为更新 UI 需要一些时间,所以我决定将它放在一个新线程中。这减少了闪烁,但没有解决它。

接下来,我决定给新线程低优先级,因为每秒重绘 60 次的屏幕部分更为重要。这再次减少了闪烁,但它仍然发生。然后,我决定在调用update()方法之前在新线程中使用Thread.sleep(150);,彻底解决了我系统上的闪烁效果。

但是,在其他系统上运行它时,它仍然会发生。不像以前那么频繁(可能每 20 秒一次),但它仍然很烦人。显然,仅在另一个线程中更新 UI 并不能解决问题。

任何想法如何完全消除闪烁?

【问题讨论】:

标签: java multithreading swing game-loop


【解决方案1】:

SwingUtilities.invokeAndWait() 中调用update(),这会停止线程并在 EDT 中更新 UI。

【讨论】:

  • 你开始线程。当您需要更改 GUI 中的某些内容时,您可以调用 SwingUtilities.invokeAndWait(您在 Runnable 中的代码)
  • 我已经用我当前的代码编辑了我的问题。知道有什么问题吗?谢谢
  • 哦,没关系,显然这只是一个尝试/捕获。现在测试,谢谢
【解决方案2】:

问题是您正在使用Thread.sleep(int),在Concurency in Swingexample 演示通过使用Thread.sleep(int)example for Runnable#Thread 来演示冻结 GUI 中更多在 EventDispatchTread 期间停止和冻结 GUI

如果您想延迟 Swing 中的任何内容,那么最好的方法是实现 javax.swing.Timer

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 2018-11-03
    • 2012-04-05
    • 2019-07-09
    • 1970-01-01
    • 2017-01-01
    • 2011-09-07
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多