2016-01-22 226 views
0

我在JFace中很新,並且遇到一些問題,無法理解爲什麼我的關閉偵聽器無法正常工作。 我修改一個簡單的JFace例如:在JFace應用程序中未觸發關閉事件

public class JFaceExample extends ApplicationWindow { 
    private ExitAction exitAction; 

    public JFaceExample() { 
    super(null); 
    exitAction = new ExitAction(this); 
    addMenuBar(); 
    addStatusLine(); 
    addToolBar(SWT.FLAT | SWT.WRAP); 
    } 

    @Override 
    protected void configureShell(Shell shell) { 
    super.configureShell(shell); 
    shell.setText("JFace File Explorer"); 
    shell.addListener(SWT.Show, new Listener() { 
     @Override 
     public void handleEvent(Event e) { 
     System.out.println("show"); 
     } 
    }); 
    shell.addListener(SWT.Close, new Listener() { 
     @Override 
     public void handleEvent(Event e) { 
     System.out.println("close"); 
     } 
    }); 
    } 

    @Override 
    protected Control createContents(Composite parent) { 
    setStatus("JFace Example v1.0"); 
    return parent; 
    } 

    @Override 
    protected MenuManager createMenuManager() { 
    MenuManager menuBar = new MenuManager(""); 
    MenuManager fileMenu = new MenuManager("&File"); 
    MenuManager helpMenu = new MenuManager("&Help"); 
    menuBar.add(fileMenu); 
    menuBar.add(helpMenu); 
    fileMenu.add(exitAction); 
    return menuBar; 
    } 

    @Override 
    protected StatusLineManager createStatusLineManager() { 
    StatusLineManager slm = new StatusLineManager(); 
    slm.setMessage("Hello, world!"); 
    return slm; 
    } 

    @Override 
    protected ToolBarManager createToolBarManager(int style) { 
    ToolBarManager toolBarManager = new ToolBarManager(style); 
    toolBarManager.add(exitAction); 
    return toolBarManager; 
    } 

    public static void main(String[] args) { 
    JFaceExample fe = new JFaceExample(); 
    fe.setBlockOnOpen(true); 
    fe.open(); 
    Display.getCurrent().dispose(); 
    } 

    private class ExitAction extends Action { 
    ApplicationWindow window; 

    public ExitAction(ApplicationWindow w) { 
     window = w; 
     setText("E&[email protected]+W"); 
     setToolTipText("Exit the application"); 
    } 

    @Override 
    public void run() { 
     window.close(); 
    } 
    } 
} 

該節目消息寫入到控制檯成功。但是,如果我點擊退出菜單項,那麼應用程序將關閉,但不會寫入關閉消息。

回答

0

當你打電話給window.close() shell關閉事件沒有被觸發,而是shell被放置(所以你可以在shell上使用一個dispose偵聽器)。

有一個在close代碼這在源代碼中的註釋:

// If we "close" the shell recursion will occur. 
// Instead, we need to "dispose" the shell to remove it from the 
// display. 
shell.dispose(); 
+0

嗯,這不是那麼好,因爲如果我使用DisposeListener那麼我將不能夠防止封閉外殼, FE通過要求退出。 – altralaser

+0

好吧,我發現我可以重寫窗口類的close方法,執行一些任務並返回true或false,具體取決於我是否要退出程序。每次執行Window.close()時,都會調用該方法,單擊GUI上的關閉按鈕或通過按Alt + F4(Windows)關閉該程序。這應該可以解決我的問題。聽衆在JFace中似乎不再需要(爲此目的)。 – altralaser

相關問題