3

为什么在以下代码中(类的一部分extends TitleAreaDialog):

@Override  
protected void createButtonsForButtonBar(Composite parent) {          
    super.createButtonsForButtonBar(parent);  
    this.getButton(IDialogConstants.OK_ID).addSelectionListener(new SelectionAdapter() {  
        @Override  
        public void widgetSelected(SelectionEvent e) {  
            okPressed();  
        }  
    });  
}  

@Override  
protected void okPressed() {  
    saveInput();  
    super.okPressed();  
}

private void saveInput(){  
    firstNameSelected = firstNameCombo.getText();  
    lastNameSelected = lastNameCombo.getText();      
}    

按下按钮时出现以下异常OK

org.eclipse.swt.SWTException: Widget 被配置在 org.eclipse.swt.SWT.error(SWT.java:4276) 的 org.eclipse.swt.SWT.error(SWT.java:4361) 在 org.eclipse。 swt.SWT.error(SWT.java:4247) 在 org.eclipse.swt.widgets.Widget.error(Widget.java:468) 在 org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:340)在 org.eclipse.swt.widgets.Combo.getText(Combo.java:1006)

在行:firstNameSelected = firstNameCombo.getText();saveInput
为什么小部件被放置在选择上?

4

2 回答 2

2

尝试createButtonsForButtonBar(Composite parent)完全删除该方法。该对话框应okPressed自行调用。

此外,我认为super.okPressed()没有必要打电话。至少我从不使用它。只是打电话this.close()

这是我使用的简单模板:

public class OptionsDialog extends Dialog {

    public OptionsDialog(Shell parentShell)
    {
        super(parentShell);
        setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
        setBlockOnOpen(true);
    }

    protected Control createDialogArea(Composite parent) {
        Composite composite = (Composite) super.createDialogArea(parent);

        GridLayout layout = new GridLayout(1, false);
        layout.marginHeight = 5;
        layout.marginWidth = 10;

        composite.setLayout(layout);

        GridData gridData = new GridData();
        gridData.widthHint = 500;

        composite.setLayoutData(gridData);

        createContent();

        return composite;
    }

    private void createContent()
    {
        /* ADD WIDGETS */
    }

    protected void configureShell(Shell newShell)
    {
        super.configureShell(newShell);
        newShell.setText("Options");
    }

    public void okPressed()
    {
        /* SAVE VALUES */
        this.close();
    }

    /* GETTERS AND SETTERS/ */

}
于 2012-10-04T16:23:30.883 回答
1

你不需要okPressed()在里面调用方法widgetSelected()。我认为根本没有必要调用widgetSelected()方法。由okPressed()对话框本身调用。

您可能想尝试以下代码。

public ClassNameWhichExtendsTitleAreDialog(Shell parentShell) {
    super(parentShell);
}

@Override
protected void createButtonsForButtonBar(Composite parent) {
    createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
    createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}

@Override
protected void okPressed() {
    firstNameSelected = firstNameCombo.getText();
    lastNameSelected = lastNameCombo.getText();
    super.okPressed();
}

// A function to return the name values obtained
于 2012-10-05T06:16:17.970 回答