Java Reference
In-Depth Information
Ask the Expert
Q
:
You explained that the action command associated with a text field can be set by
calling
setActionCommand( )
. Can I use this method to set the action command
associated with a push button?
A
:
Yes. As explained, by default the action command associated with a push button is
the name of the button. To set the action command to a different value, you can use
the
setActionCommand( )
method. It works the same for
JButton
as it does for
JTextField
.
To obtain the string that is currently displayed in the text field, call
getText( )
on the
JTextField
instance. It is declared as shown here:
String getText( )
You can set the text in a
JTextField
by calling
setText( )
, shown next:
void setText(String
text
)
Here,
text
is the string that will be put into the text field.
The following program demonstrates
JTextField
. It contains one text field, one push
button, and two labels. One label prompts the user to enter text into the text field. When
the user presses
ENTER
while focus is within the text field, the contents of the text field
are obtained and displayed within a second label. The push button is called Reverse. When
pressed, it reverses the contents of the text field. Sample output is shown in
Figure 16-3
.