简体   繁体   English

用于算法的Java swing接口

[英]Java swing interface for algorithm

I am trying to build a Swing GUI for an algorithm I am developing. 我正在尝试为正在开发的算法构建Swing GUI。 During its running, the algorithm will modify the GUI constantly. 在运行过程中,该算法将不断修改GUI。 I have read that the long-running tasks should be separated from the GUI and that modifying the swing components should be done from the EDT thread. 我已经读到,应将长时间运行的任务与GUI分开,并应从EDT线程完成对摆动组件的修改。 However, what I need is sort of an overlapping between these two: running the algorithm, the algorithm makes some changes, these changes must be reflected in the GUI, the algorithm continues its execution, makes another changes, which again must be reflected in the GUI and so on. 但是,我需要在这两者之间有点重叠:运行算法,算法进行一些更改,这些更改必须反映在GUI中,算法继续执行,进行另一个更改,这又必须反映在GUI等。

Could you give me some advice on what I should use to accomplish my objective? 您能给我一些有关我应该用来实现目标的建议吗?

Thank you in advance. 先感谢您。

You should use SwingUtilities.invokeLater for this: 您应该为此使用SwingUtilities.invokeLater

public class MyAlgorithm {

    void doAlgorithm() {
        while(notDone()) {
            // Iterative work
            ...
            // Update the UI
            if(shouldUpdateUI()) {
                SwingUtilities.invokeLater(() -> {
                    // UI update code goes here
                });
            }
        }
    }
}

If you're not using Java 8, just replace the lambda ( () -> { ... } ) with a Runnable : 如果您不使用Java 8,只需将Lambda( () -> { ... } )替换为Runnable

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        // UI update code goes here
    }
});

Beware though that the UI will be updated on another thread so you may have to take a defensive copy of your state and update the UI based on that. 请注意,虽然UI会在另一个线程上更新,所以您可能必须获取状态的防御性副本并根据该状态更新UI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM