Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

How to close all open dialogs of a given SWT shell?

My program opens a dialog (on a given shell):

new FileDialog(shell).open();

My Question is: How can I (in another part of my program) close all open dialogs of a given shell?

private void closeDialogs(Shell shell) {
    // how to close open dialogs?
}

Below is minimal test case, one button opens the dialogs. The other button should close all open dialogs of the current shell.

enter image description here

public static void main(final String[] args) {
    final Display display = new Display();

    final Shell shell = new Shell(display);
    shell.setText("Testcase");
    shell.setLayout(new FillLayout());

    final Button button = new Button(shell, SWT.PUSH);
    button.setText("Open Dialog");
    button.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            new NonModalDialog(shell).open();
        }
    });

    Button button2 = new Button(shell, SWT.PUSH);
    button2.setText("Close open dialogs");
    button2.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            // How to close all open dialogs of the given shell?
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
}

Upvotes: 1

Views: 691

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328614

You will have to collect the dialogs in a list as you open them.

When the "close" button is clicked, walk through the list and close the dialogs.

Note: This will not work when any of the dialogs are modal. A modal dialog will take over the event loop and ignore any events that aren't directed at itself, so clicking on the button will be impossible.

Upvotes: 1

Related Questions