12

我有以下 SWT 测试代码:

public static void main(String[] args) {
    shell = new Shell();
    shell.setText(APP_NAME + " " + APP_VERSION);
    shell.addShellListener(new ShellListener() {
        public void shellActivated(ShellEvent event) { }
        public void shellClosed(ShellEvent event) { exit(); }
        public void shellDeactivated(ShellEvent event) { }
        public void shellDeiconified(ShellEvent event) { }
        public void shellIconified(ShellEvent event) { }
    });     
    shell.open();
    display = shell.getDisplay();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

我的 exit() 方法如下:

private void exit() {
    System.exit(0);
}

我尝试通过关闭外壳(“窗口”)或拉下应用程序菜单(标记为“SWT”)并选择“退出”来退出应用程序。

当我这样做时,在 Dock 中留下了一个 SWT 存根,并且 SWT 应用程序实际上并没有退出。我必须通过 Eclipse 或 Force Quit 手动终止 SWT 应用程序。

我已经在 Mac OS X 10.5.6 (Intel) 下的 Eclipse 3.4.1 下使用 v3.4 和 v3.5 SWT jar 进行了尝试。

当我关闭 shell 时,我需要做额外的工作才能退出应用程序吗?

4

2 回答 2

10

您没有正确释放本机资源 - 您有资源泄漏。

你不需要这样做:

private void exit() {
    System.exit(0);
}

main 方法将在 shell 被释放时退出。如果必须使用退出方法,请在处理完所有 SWT 资源后调用它:

    Display display = new Display();
    try {
        Shell shell = new Shell(display);
        try {
            shell.open();
            while (!shell.isDisposed()) {
                if (!display.readAndDispatch()) {
                    display.sleep();
                }
            }
        } finally {
            if (!shell.isDisposed()) {
                shell.dispose();
            }
        }
    } finally {
        display.dispose();
    }
    System.exit(0);
于 2009-01-27T13:03:02.600 回答
2

当您分配外壳时:

shell = new Shell();

一些本地资源也随之分配。在退出应用程序之前,您必须处理这些资源:

私人无效退出(){
    shell.dispose();
    System.exit(0);
}

当然,您必须为您的 exit() 方法提供“shell”变量才能执行此操作。

请注意,我认为您不需要处置 Display,因为您没有使用“ new Display()”创建它。但是,您使用 SWT 创建的任何内容(JavaDoc 中记录的少数项目除外)new都必须在完成后处理掉。否则你会泄露原生资源。

于 2009-01-27T14:36:34.390 回答