Unni Kris
Unni Kris

Reputation: 3105

Error in OK button selection listener in a SWT/JFace Dialog

I am receiving the below exception while trying to access the field value from a text field within a SWT Dialog, from the selection listener of the 'OK' button.

org.eclipse.swt.SWTException: Widget is disposed

I can understand the error is because the Dialog is already disposed when I am trying to access it. But i haven't made any explicit call to dispose the shell.

Is the Dialog disposed automatically on clicking the 'OK' button? Is there any way it can be overridden? Or Am i doing something wrong here?

Appreciate any help or pointers. Relevant code snippet below:

public class MyDialog extends Dialog {

    /** The file Name Text field. */
    private Text fileNameText;

    /** The constructor. **/
    protected MyDialog(Shell parentShell) {
        super(parentShell);
    }

    /** Create Dialog View. **/
    protected Control createDialogArea(Composite parent) {
        Composite mainComposite = (Composite) super.createDialogArea(parent);

        fileNameText = new Text(mainComposite, SWT.BORDER);
        fileNameText.setText("");
        fileNameText.setBounds(0, 20, 428, 20);

        return mainComposite;
    }

    /** Override method to set name and listener for 'OK' button. **/
    protected void createButtonsForButtonBar(Composite parent) {
        super.createButtonsForButtonBar(parent);

        Button submitButton = getButton(IDialogConstants.OK_ID);
        submitButton.setText("Review");
        setButtonLayoutData(submitButton);

        // Perform Selected CleanUp activity on Submit Click.
        submitButton.addSelectionListener(new SelectionListener() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                // do something.
                if (fileNameText.getText().isEmpty()) {
                        return;
                }
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent e) {
            }
        });
    }
}

Upvotes: 0

Views: 2090

Answers (1)

greg-449
greg-449

Reputation: 111217

Yes the dialog is automatically disposed when the OK button is clicked and No you should not stop this.

What you must do is override okPressed and save the text value before the dialog is disposed:

private String fileNameValue;

....

@Override
protected void okPressed()
{
  fileNameValue = fileNameText.getText();

  super.okPressed();
}

Upvotes: 2

Related Questions