Java Reference
In-Depth Information
For some applications, you may also want to remove keystrokes from the key map. For
instance, the JTextField has an entry in the key map for the Enter key so that any registered
ActionListener objects are notified. If the JTextField is on a screen where a button has been
designated as the default, pressing Enter won't select the default button, as desired. Getting rid
of the default behavior is a simple process of requesting the removal of the single KeyStroke
from the Keymap , as shown here:
Keymap keymap = textField.getKeymap();
KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
keymap.removeKeyStrokeBinding(keystroke);
Then, when you press Enter in the text field, the default button is activated, as shown in
Figure 15-13.
Figure 15-13. Using the default button after removing the Enter binding from the Keymap
The program source for the example in Figure 15-13 is shown in Listing 15-12.
Listing 15-12. Working with the Default Button
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
public class DefaultSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Default Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
frame.add(textField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand() + " selected");
}
};
 
Search WWH ::




Custom Search