Nicolas400
Nicolas400

Reputation: 85

Jface Dialog, How to retrieve correctly what button pressed the user?

I'm having troubles with a custom Dialog in Eclipse.

in the first place, I created a Class that extend Dialog.

    public class ModificarGrupoBCDialog extends Dialog {

    private static final int CANCELAR = 999;
    private static final int MODIFICAR = 1;
    ...

somewhere I create the buttons...

    protected void createButtonsForButtonBar(Composite parent) {
    this.createButton(parent, MODIFICAR, "Modificar", true);
    this.getButton(MODIFICAR).setEnabled(puedeAltaGrupoBC());
    this.bt_ok = this.getButton(MODIFICAR);

    this.createButton(parent, CANCELAR, "Cancelar", false);

    Display display = window.getShell().getDisplay();
    Image image = new Image(display, ModificarGrupoBCDialog.class.getResourceAsStream("/icons/modificar.png"));
    this.getButton(MODIFICAR).setImage(image);
    image = new Image(display, ModificarGrupoBCDialog.class.getResourceAsStream("/icons/cancelar.png"));
    this.getButton(CANCELAR).setImage(image);

}

and when the user clicks...

    protected void buttonPressed(int buttonId) {
    switch (buttonId) {
    case MODIFICAR:
                // Some Code, for Change Button

        break;
    case CANCELAR:
        setReturnCode(CANCELAR);
        close();
        break;
    }

Finally, this is how I open and get the returnCode, in the caller object.

            ...
            ModificarGrupoBCDialog modificarGrupoBC = new ModificarGrupoBCDialog(window.getShell(), window, gr_bc);
            if (modificarGrupoBC.getReturnCode() == Window.OK) {
                  //... Some code on OK
            } else {
                //another code when cancel pressed.
            }
            ;

as you can see, after trying a while, I have to write setReturnCode() in CANCELAR switch block, is that OK ? I spect that Dialog class automatically asign the correct return code.

May be someone could point me to a good sample.

I'm reading Vogela's blog, and may be the solution is to override okPressed() method ?

Best Regards.

Upvotes: 1

Views: 1122

Answers (1)

greg-449
greg-449

Reputation: 111142

The standard dialog sets the return code in two places:

protected void okPressed() {
    setReturnCode(OK);
    close();
}

protected void cancelPressed() {
    setReturnCode(CANCEL);
    close();
}

so your code doing:

setReturnCode(xxxx);
close();

should be fine as long as the button id you are using does not match the Cancel or OK button ids.

You could also use the approach used by MessageDialog which simply does this:

protected void buttonPressed(int buttonId) {
    setReturnCode(buttonId);
    close();
}

Upvotes: 3

Related Questions