首页 > 解决方案 > 尝试从 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");

    }
}

标签: javaeclipseswing

解决方案


推荐阅读