Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
May 31, 2006

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);
    }

}
Milan Zivkovic
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap