Java Reference
In-Depth Information
JPanel panel = new JPanel();
JButton defaultButton = new JButton("Default Button");
defaultButton.addActionListener(actionListener);
panel.add(defaultButton);
JButton otherButton = new JButton("Other Button");
otherButton.addActionListener(actionListener);
panel.add(otherButton);
frame.add(panel, BorderLayout.SOUTH);
Keymap keymap = textField.getKeymap();
KeyStroke keystroke =
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
keymap.removeKeyStrokeBinding(keystroke);
frame.getRootPane().setDefaultButton(defaultButton);
frame.setSize(250, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
JTextComponent.KeyBinding Class
The
JTextComponent
class stores the specific key bindings with the help of the
JTextComponent.KeyBinding
class. The current look and feel defines the default set
of the key bindings for text components, such as the familiar Ctrl-X for cut, Ctrl-C for
copy, and Ctrl-V for paste on a Microsoft Windows platform.
Handling JTextField Events
Dealing with events in Swing text components is completely different from dealing with events
in AWT text components. Although you can still attach an
ActionListener
to listen for when the
user presses the Enter key in the text field, attaching a
KeyListener
or a
TextListener
is no
longer useful.
To validate input, it is better to attach an
InputVerifier
than a
FocusListener
. However,
input validation tends to be best left to the
Document
to accomplish or implemented when a
user submits a form.
Listening to JTextField Events with an ActionListener
The
JTextField
will notify any registered
ActionListener
objects when the user presses Enter
from within the text field. The component sends an
ActionEvent
to the
ActionListener
objects.