java - 尝试从 SwingWorker 更新时,Swing UI 冻结
问题描述
我尝试制作一个简单的 Swing 示例,它使用 SwingWorker 来更新标签的文本。每当 SwingWorker 完成并尝试更新文本时,UI 都会冻结。关闭窗口后,它会显示 AWT-EventQueue-0 "Widget is disposed" 异常。
我试图确保它在 EDT 等上运行,但我认为我在这里遗漏了一些非常基本的东西。有人可以看看我的代码并告诉我可能会发生什么吗?
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
public class MySwingWindow {
private Label mainText;
protected Shell shell;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MySwingWindow window = new MySwingWindow();
window.open();
}
});
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
try {
SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() throws Exception {
for (int i = 0; i <= 2; i++) {
Thread.sleep(1000);
System.out.println("Running " + i);
}
return true;
}
@Override
protected void done() {
mainText.setText("Done");
}
};
worker.execute();
} catch (Exception e) {
e.printStackTrace();
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(450, 300);
shell.setText("SWT Application");
mainText = new Label(shell, SWT.NONE);
mainText.setBounds(78, 84, 55, 15);
mainText.setText("Working");
}
}
解决方案
推荐阅读
- javascript - 如何绕过 WSO2 IS 登录页面?
- python - 为什么当 Numpy 不进行点积计算时,Dask 数组会引发内存错误?
- powershell - 使用 PowerShell 从 .reg 文件更改二进制注册表值
- visual-studio - 使用 Visual Studio 2017 和 TFS Build 2015 的工具版本
- latex - bookdown pdf输出中缺少数字
- java - NoSuchMethodException:springframework.boot.autoconfigure.http.HttpMessageConverters
- sql - ">= 是什么意思?在 SQL 中是什么意思?
- matlab - 有人可以解释这段代码吗
- hadoop - 将可选属性从主 oozie 工作流传递到子工作流
- reactjs - Jest 用箭头函数测试 JSX 元素