[JAVA Notes]Firing Focused JButtons with the ENTER Key

Most users of GUI software know they can move the focus from one control to another by pressing the tab key. There is usually some visual cue to let them know which control has the current focus, for example, when a JButton acquires the focus a small box will appear around its label text.


Most GUI users also expect that when a control, in particular a button, has the focus, they can activate it by pressing the ENTER key. With Swing applications, however, this may not always be the case; in fact, pressing the ENTER key may sometimes activate a button that the user emphatically does not want to be activated.


This is due to a change that was made to the Metal look-and-feel in Java 1.2. This is the default look-and-feel for Swing apps, and until version 1.2 it behaved the way most users expect it to, with the ENTER key activating a focused JButton. Since version 1.2 though, pressing ENTER will not activate a focused JButton in a Swing app using the Metal look-and-feel. Instead, the user must press the spacebar to activate the focused JButton. Suppose a user is presented with a Yes/No JOptionPane dialog that asks, "Do you want to delete all of your files?" If the user tabs the focus over to the No button and presses ENTER, the Yes button—the default button for the JOptionPane—will be activated instead.


Here is a simple static method that accepts a JButton argument, that will alter the JButton so that pressing the ENTER key will activate it when it is focused, provided that is the action caused by pressing the spacebar:



public static void enterPressesWhenFocused
(JButton button) {

button.registerKeyboardAction(
button.getActionForKeyStroke(
KeyStroke.getKeyStroke(
KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);

button.registerKeyboardAction(
button.getActionForKeyStroke(
KeyStroke.getKeyStroke(
KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);

}

留言

這個網誌中的熱門文章

<備忘>都是電池惹的禍......!?

それぞれに

Google推出自有Web Browser--Chrome