Is it possible not to use the Alt key combination? Eg I have a form with 2 buttons - submit and cancel - with multiple text fields. When I hit "Enter" or "Return" it triggers the submit button.
In another words, how to setMnemonic without using Alt key?
Here's what the method says:
public void setMnemonic(int mnemonic)
Sets the keyboard mnemonic on the current model. The mnemonic is the key which when combined with the look and feel's mouseless modifier (usually Alt) will activate this button if focus is contained somewhere within this button's ancestor window.
A mnemonic must correspond to a single key on the keyboard and should be specified using one of the VK_XXX keycodes defined in java.awt.event.KeyEvent. Mnemonics are case-insensitive, therefore a key event with the corresponding keycode would cause the button to be activated whether or not the Shift modifier was pressed.
If the character defined by the mnemonic is found within the button's label string, the first occurrence of it will be underlined to indicate the mnemonic to the user.
mnemonic - the key code which represents the mnemonic
So I think if you can modify the mouseless modifier in the 'look and feel' it is doable, although using alt for mnemonics is a standard most users are used to.
Note that this is just a (poor) proof of concept. I would not want to see any real code go out like this. In particular, I am cheating by setting the key listener to the JPanel, then resetting the focus to the JPanel whenever anything happens. This results in the very poor experience that the user will never see focus where they want it. You would probably be much better off having a common key listener that gets assigned to each field (and button), so no matter where the focus is, the Enter key will still work in a desirable manner.
So, in fact you have 4 ways to "press" a button:
- mnemonic (Alt + key)
- accelerator key (key)
- default button (only one per root pane - Enter)
- when a button has focus (Space)