Jay Imerman
Jay Imerman

Reputation: 4600

How to close a Java SWT window with a button?

As a newbie to Java, and many years of iOS and .NET experience, I found this to be massively confusing. What I want I thought would be very simple - I want a dialog (called from a main window) with OK and Cancel buttons. When you click OK, it does something, then dismisses the dialog. When you click Cancel, it just dismisses the dialog.

However, doing this using the SWT shell Dialog class is not obvious. How do you get a button to dismiss the dialog, and return execution back to the main Window?

Upvotes: 4

Views: 12918

Answers (2)

greg-449
greg-449

Reputation: 111140

Use Shell.close() rather than dispose() - so shlCheckOut.close().

Shell.close sends the SWT.Close event and then calls dispose.

Upvotes: 5

Jay Imerman
Jay Imerman

Reputation: 4600

With some trial-and-error and a lot of fruitless searching, I found in your button code, you have to call the .dispose() method of the dialog's shell variable. For example, my dialog is CheckOutDialog, thus I named the shell variable shlCheckOut. In the createContents() method, I put the button code as such:

...

Button btnCancel = new Button(shlCheckOut, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
    @Override
        public void widgetSelected(SelectionEvent e) {
            shlCheckOut.dispose();
        }
    }
}

Upvotes: 4

Related Questions