Java Reference
In-Depth Information
The method
getText
is an input method, and the method
setText
is an output
method. The method
setText
can be used to display a new text string in a text field.
For example, the following will cause the text field
name
to change the text it displays
to the string
"This is some output"
:
name.setText("This is some output");
The following line from the method
actionPerformed
in Display 17.17 uses both
getText
and
setText
:
name.setText("Hello " + name.getText());
This line changes the string in the text field
name
to
"Hello "
followed by the old
string value in the text field. The net effect is to insert the string
"Hello "
in front of
the string displayed in the text field.
getText
and
setText
The classes
JTextField
and
JTextArea
both contain methods called
getText
and
set-
Text
. The method
getText
can be used to retrieve the text written in the text field or text
area. The method
setText
can be used to change the text written in the text field or text
area.
SYNTAX
Name_of_Text_Component
.getText()
returns the text currently displayed in the text field
or text area.
Name_of_Text_Component
.setText(
New_String_To_Display
);
EXAMPLES
String inputString = ioComponent.getText();
ioComponent.setText("Hello out there!");
ioComponent
may be an instance of either of the classes
JTextField
or
JTextArea
.
A
text area
is an object of the class
JTextArea
. A text area is the same as a text field
except that it allows multiple lines. Two parameters to the constructor for
JTextArea
specify the minimum number of lines and the minimum number of characters per line
that are guaranteed to be visible. You can enter any amount of text in a text area, but
only a limited number of lines and a limited number of characters per line will be visi-
ble. For example, the following creates a
JTextArea
named
theText
that will have at
least 5 lines and at least 20 characters per line visible:
text area
JTextArea
JTextArea theText =
new
JTextArea(5, 20);