我的项目是基于 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()
更新您的模型,它执行在美国东部时间。在这个example ,JTable
对应你的View
,TableModel
对应你的Model
。请注意,JTable
监听它自己的 TableModel
。
关于java - 在 Swing 的 EDT 中实现线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716901/