2

我目前有一个 JFrame,在它的内容窗格上,我以每秒 60 帧的速度从游戏循环中绘制图像。这是正常的,但在右侧,我现在有更多的Swing Elements,我想在选择内容窗格的某些部分时显示一些信息。该部分是静态 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 次的屏幕部分更为重要。这再次减少了闪烁,但它仍然发生。然后,我决定Thread.sleep(150);在调用 update() 方法之前在新线程中使用,这完全解决了我系统上的闪烁效果。

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

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

4

2 回答 2

4

调用update()in SwingUtilities.invokeAndWait()which 停止线程并更新 EDT 中的 UI。

于 2011-11-22T09:33:58.650 回答
3

问题是您正在使用,在 Swing中的Concurency 中Thread.sleep(int)停止和冻结 GUI ,例如使用Runnable#Thread示例演示冻结 GUIEventDispatchTreadThread.sleep(int)

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

于 2011-11-22T09:31:40.893 回答