我尝试制作一个简单的Swing示例,该示例使用SwingWorker更新Label的文本。只要SwingWorker完成并尝试更新文本,UI就会冻结。关闭窗口后,它将显示AWT-EventQueue-0“已放置小部件”异常。
我试图确保它在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");
}
}