Java Reference
In-Depth Information
When the Enter key is pressed within the
JTextField
, it automatically notifies any registered
ActionListener
implementations.
Creating a JTextField
There are five constructors for the
JTextField
component:
public JTextField()
JTextField textField = new JTextField();
public JTextField(String text)
JTextField textField = new JTextField("Initial Text");
public JTextField(int columnWidth)
JTextField textField = new JTextField(14);
public JTextField(String text, int columnWidth)
JTextField textField = new JTextField("Initial Text", 14);
public JTextField(Document model, String text, int columnWidth)
JTextField textField = new JTextField(aModel, null, 14);
By default, you get an empty text field, zero columns wide, with a default initial model. You
can specify the initial text for the
JTextField
and how wide you want the component to be.
Width is specified as the number of
m
characters in the current font that will fit within the
component. There's no restriction on the number of characters that can be input. If you specify
the
Document
data model in the constructor, you will probably want to specify a
null
initial-text
argument. Otherwise, the current contents of the document will be replaced by the initial text for
the text field.
Using JLabel Mnemonics
In the discussion of mnemonics in Chapter 4, you learned that the various button classes can
have a keyboard shortcut that causes the button component to be selected. The special mnemonic
character is usually underlined to indicate this visually. If the user presses the mnemonic character,
along with a platform-specific mnemonic activation key, such as Alt for both Windows and
UNIX, the button is activated/selected. You can provide a similar capability for a
JTextField
,
and all other text components, with the help of a
JLabel
.
You can set the display mnemonic for a label, but instead of selecting the label when the
mnemonic key is pressed, selection causes an associated component to get the input focus.
The display mnemonic is set with the
public void setDisplayedMnemonic(character)
method,
in which
character
is either an
int
or a
char
. Using the
KeyEvent
constants when changing the
mnemonic setting simplifies initialization considerably.
The following source demonstrates how to interconnect a specific
JLabel
and
JTextField
.
JLabel label = new JLabel("Name: ");
label.setDisplayedMnemonic(KeyEvent.VK_N);
JTextField textField = new JTextField();
label.setLabelFor(textField);