Firing Focused JButtons with the ENTER Key

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 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. This simple static method alters a JButton passed to it so that pressing the ENTER key activates the button when it has focus:

import java.awt.event.KeyEvent;import javax.swing.JButton;import javax.swing.JComponent;import javax.swing.KeyStroke;public class EnterButton extends JButton {        public EnterButton(String name){        super(name);                super.registerKeyboardAction(                super.getActionForKeyStroke(                        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),                        KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),                        JComponent.WHEN_FOCUSED);        super.registerKeyboardAction(                super.getActionForKeyStroke(                        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),                        KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),                        JComponent.WHEN_FOCUSED);    }}
See also  How to Avoid Money Transfer Scams  

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist