How do I define a default button per form?

Hello there,

I was trying to create a window containing 2 (two) forms.
Both forms define a default button like that:

btn.setClickShortcut(KeyCode.ENTER);
btn.addStyleName("default");

As a result, the action of the 2nd button is executed when the user presses enter - regardless of the form having the focus.
This is perfectly aligned with the API docs of the Button class (“The shortcut is global (bound to the containing Window).”)

    /**
     * Makes it possible to invoke a click on this button by pressing the given
     * {@link KeyCode} and (optional) {@link ModifierKey}s.<br/>
     * The shortcut is global (bound to the containing Window).
     * 
     * @param keyCode
     *            the keycode for invoking the shortcut
     * @param modifiers
     *            the (optional) modifiers for invoking the shortcut, null for
     *            none
     */
    public void setClickShortcut(int keyCode, int... modifiers) { ...


My question is:
How do I define a default button per form?

If the focus is in one of the fields of Form A, and the user presses enter, Vaadin should “press” the default button defined for Form A.
If the focus is in one of the fields of Form B, and the user presses enter, Vaadin should “press” the default button defined for Form B.

Don’t know about an official solution but you could fake it by adding FocusListeners to the forms/fields. when form1/ a field in form one is selected, a FocusListener adds the clickShortcut to the form 1 button, and then a BlurListener removes the click shortcut. same for form2 and form2 button. This guarantees that enter works only when one of the forms is focused, and that the press goes to the correct button.

sounds like a hack … but I’ll give it a shot

Thanks!

It’s possible to add keyboard shortcuts to Panels, so I would try to do this so that I create two Panels and wrap the Forms inside the Panels. Then just add a keyboard short cut to both Panels.

Maybe better to do it as Henri suggested as you wouldn’t have to upkeep the state of the shortcuts yourself.

Correction: That two lines of code in the original post use the wrong style name for a default button. Should be “primary” not “default” in Vaadin 6.

btn.setClickShortcut(KeyCode.ENTER);
btn.addStyleName("primary");    // "primary" not "default"  

See Section 12.6.1 of
The Book of Vaadin
.

–Basil Bourque

I’ve learned that the various themes have a string constant for the default (or “primary”) button style.

The
LiferayTheme
has no such constant.

You can see this constant in action in The Book Of Vaadin page,
Shortcut Keys for Default Buttons
.

// Have an OK button and set it as the default button
Button ok = new Button( "OK" ) ;
ok.setClickShortcut( KeyCode.ENTER ) ;
ok.addStyleName( Reindeer.BUTTON_DEFAULT ) ;