当我第二次创建新的SWT应用程序窗口时,应用程序崩溃时出现SWTException: Widget is disposed
错误。怎么了?
这是我的代码:
摘要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
(代表新窗口):
public class AboutController extends Controller {
static AboutView view = new AboutView();
public AboutController() {
super(view);
super.render();
}
}
摘要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();
}
}
}
}
我的观点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"));
}
}
当我尝试创建新的应用窗口时,new AboutController()
会出现Widget is disposed
错误。
答案 0 :(得分:10)
问题是您无法访问已经放置的窗口小部件。在您的代码中,AboutController.view
是静态的,因此在初始化类AboutController
时只创建一次。当Shell
关闭时,它会自动处理,因此所有子窗口小部件也会被处理掉 - 包括您的视图对象。
当您再次打开窗口时,已经处理好的视图将被移交给超级构造函数而不是新创建的视图。