This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
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.
You might be able to do this by setting an overall key listener for your panel. Normally this would be a bad idea as it would slow down your application, but if this is just a temporary dialog box you might be able to get away with it.
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.
Actions (and probably also buttons, but I don't know for sure - you'll have to check the javadoc yourself) allow using an ACCELERATOR_KEY, which is what you want. Also, JRootPane (JFrame.getRootPane()) has a setDefaultButton() method, which you can use for setting a default button (when you press Enter, it's action gets executed).
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)