简体   繁体   中英

SWTException: Widget is disposed

When I create open new SWT app window a second time, app crashes with SWTException: Widget is disposed error. What's wrong?

Here is my code:

ABSTRACT Controller.java :

public abstract class Controller {
    protected View view;

    public Controller(View v) {
        view = v;
    }

    protected void render() {
        data();
        view.setData(data);
        view.render();
        listeners();
        if (display)
            view.open();
    }
    protected void data() {}

    protected void listeners() {}
}

AboutController.java (represends new window):

public class AboutController extends Controller {
    static AboutView view = new AboutView();

    public AboutController() {
        super(view);
        super.render();
    }
}

ABSTRACT View.java :

public abstract class View {
    protected Display display;
    protected Shell shell;
    protected int shellStyle = SWT.CLOSE | SWT.TITLE | SWT.MIN;

    private void init() {
        display = Display.getDefault();
        shell = new Shell(shellStyle);
    };

    protected abstract void createContents();

    public View() {
        init();
    }

    public void render() {
        createContents();
    }

    public void open() {
        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
}

And my view AboutView.java

public class AboutView extends View implements ApplicationConstants {

    protected void createContents() {
        shell.setSize(343, 131);
        shell.setText("About");

        Label authorImage = new Label(shell, SWT.NONE);
        authorImage.setBounds(10, 10, 84, 84);
        authorImage.setImage(SWTResourceManager.getImage(AboutView.class,
                "/resources/author.jpg"));
    }
}

When I try to create new app window, with new AboutController() then Widget is disposed error occurs.

The problem is that you cannot access an already disposed widget. In your code, AboutController.view is static, so it is created only once when the class AboutController is initialized. When the Shell is closed, it is automatically disposed and so all child-widgets get disposed too - including your view object.

When you then open the window a second time, the already disposed view is handed over to the super-constructor instead of a newly created view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM