java - 在 Swing 的 EDT 中实现线程?

标签 java multithreading swing swingworker

我的项目是基于 Java 的 Swing 库构建的。它生成显示我的 GUI(可以正常工作)的 EDT。

程序入口,初始化EDT:

public final class Main {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Start());
    }

    class Start implements Runnable {
        private Model model = new Model();
        private Controller controller = new Controller(model);
        private View view = new View(controller);

        @Override
        public void run() {
            // Initialize the view and display its JFrame...
        }
    }
}

但是,当在我的 GUI 中单击按钮/单选框等时,Controller 类必须对模型执行操作。

我的问题如下:

  • 我应该将 Controller 的代码包装在一个新的 SwingWorker 中吗?
    • 如果不是,我是否应该将我的模型代码包装在一个新的 SwingWorker 中?
  • 如果我用线程包装 Controller 的代码,我是否需要同步模型中的共享状态变量?
  • 如果我的模型在新线程上运行,将更改通知我的 GUI,这会发生在 EDT 还是新线程上?

例如:

public class Controller {
    public void updateModel() {
        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                model.somethingSomethingSomething();
            }
        }.execute();
    }
}

public class Model {
    public void somethingSomethingSomething() {
        notifyListeners(); // This is going to notify whichever GUI 
                           // is listening to the model.
                           // Does it have to be wrapped with Swing.invokeLater?
    }
}

public class View {
    // This function is called when the model notifies its listeners.
    public void modelChangedNotifier() {
        button.setText("THE MODEL HAS CHANGED"); // Does this occur on the EDT?
    }
}

最佳答案

不是从 doInBackground() 更新您的模型,publish() 中间结果并从 process() 更新您的模型,它执行在美国东部时间。在这个exampleJTable对应你的ViewTableModel对应你的Model。请注意,JTable 监听它自己的 TableModel

关于java - 在 Swing 的 EDT 中实现线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716901/

相关文章:

java - GoogleSignIn.getLastSignedInAccount() 返回具有空字段的帐户

成功连接和写入次数后 Java 连接超时

java - 每小时运行一次 Java 代码

ios - 调用 didEnterBackground 后是否可以在主线程上执行某些操作?

java - JFreeChart y 轴图例随着小数字消失

Java - Maven - 在表单中设置图标图像

java - Spring Boot 从我的模型和存储库类创建一个库

java - 是否可以调用默认构造函数而不是零参数构造函数?

multithreading - 使用静态 C++ lib 的 Windows 8 WinRT 应用程序具有多个为 vccorlibd 定义的符号

java - 在java中显示图像需要RAM