2013-11-21 16 views
2

當我第二次創建新的SWT應用程序窗口時,應用程序崩潰,出現SWTException: Widget is disposed錯誤。怎麼了?SWTException:部件已配置

這裏是我的代碼:

摘要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新窗口):

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錯誤。

+1

你爲什麼不發佈異常堆棧跟蹤? – isnot2bad

回答

8

問題是您無法訪問已經部署的小部件。在你的代碼中,AboutController.view是靜態的,所以當初始化類AboutController時它只創建一次。當關閉Shell時,它會自動處理,因此所有子窗口小部件也會被處理 - 包括您的視圖對象。

當您再次打開該窗口時,已處理的視圖將切換到超級構造函數而不是新創建的視圖。

+0

+1斑點很好 – Baz

+0

謝謝,我明白了。但如何初始化視圖並將其發送到超級?超(新AboutView())是好的,但視圖保持未定義... – ovnia

+0

@ user3017651然後刪除靜態字段。除此之外,你不應該在構造函數中做所有事情!只需初始化你的對象,但不要做任何渲染,打開等! – isnot2bad