使用SWT显示父模式对话框

Mot*_*Mot 13 java swt modal-dialog

AWT/Swing允许显示应用程序模式(阻止整个应用程序)和父模式(仅阻止父项)对话框.如何通过SWT实现同样的目标?

Jea*_*let 24

为了阻止整个应用程序,您可以创建Shell带有样式的对话框SWT.APPLICATION_MODAL,打开它,然后抽取UI事件直到shell被释放:

Display display = Display.getDefault();
Shell dialogShell = new Shell(display, SWT.APPLICATION_MODAL);
// populate dialogShell
dialogShell.open();
while (!dialogShell.isDisposed()) {
    if (!display.readAndDispatch()) {
        display.sleep();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您只想阻止对父项的输入,请尝试使用该样式SWT.PRIMARY_MODAL,尽管Javadocs指定(对于其他模态样式)这是一个提示; 也就是说,不同的SWT实现可能不会以相同的方式完全处理它.同样,我不知道一种符合SWT.SYSTEM_MODAL风格的实现.


更新:回答第一条评论

如果您同时打开两个或更多主要模态,则在模态关闭之前不能使用技巧来抽取事件,因为它们可以按任何顺序关闭.代码将运行,但在当前对话框关闭后的while循环之后以及之后打开的所有其他此类对话框将继续执行.在这种情况下,我会DisposeListener在每个对话框上注册一个,以便在它们关闭时获得回调.像这样的东西:

void run() {
    Display display = new Display();
    Shell shell1 = openDocumentShell(display);
    Shell shell2 = openDocumentShell(display);

    // close both shells to exit
    while (!shell1.isDisposed() || !shell2.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

Shell openDocumentShell(final Display display) {
    final Shell shell = new Shell(display, SWT.SHELL_TRIM);
    shell.setLayout(new FillLayout());
    Button button = new Button(shell, SWT.PUSH);
    button.setText("Open Modal Dialog");
    button.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            System.out.println("Button pressed, about to open modal dialog");
            final Shell dialogShell = new Shell(shell, SWT.PRIMARY_MODAL | SWT.SHEET);
            dialogShell.setLayout(new FillLayout());
            Button closeButton = new Button(dialogShell, SWT.PUSH);
            closeButton.setText("Close");
            closeButton.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    dialogShell.dispose();
                }
            });
            dialogShell.setDefaultButton(closeButton);
            dialogShell.addDisposeListener(new DisposeListener() {
                @Override
                public void widgetDisposed(DisposeEvent e) {
                    System.out.println("Modal dialog closed");
                }
            });
            dialogShell.pack();
            dialogShell.open();
        }
    });
    shell.pack();
    shell.open();
    return shell;
}
Run Code Online (Sandbox Code Playgroud)

  • (顺便说一句,SWT.SHEET样式特别适合这些PRIMARY_MODAL对话框.在Mac OS X上,它们会使对话框显示出父对象的标题栏,并且明显地附在父对象上,清楚地标明它阻止与其父级的UI交互.不知道在其他平台上发生了什么......) (2认同)