Java Reference
In-Depth Information
The following statements create an empty text field that has enough space for roughly 60
characters and a text field of the same size with the starting text “Enter RSS feed URL
here”:
JTextField rssUrl = new JTextField(60);
JTextField rssUrl2 = new JTextField(
“Enter RSS feed URL here”, 60);
Text fields and text areas both inherit from the superclass
JTextComponent
and share
many common methods.
The
setEditable(
boolean
)
method determines whether a text component can be edited
(
true
) or not (
false
). There's also an
isEditable()
method that returns a corresponding
boolean
value.
The
setText(
String
)
method changes the text to the specified string, and the
getText()
method returns the component's current text as a string. Another method
retrieves only the text that a user has highlighted in the
getSelectedText()
component.
Password fields
are text fields that hide the characters a user is typing into the field. They
are represented by the
JPasswordField
class, a subclass of
JTextField
. The
JPasswordField
constructor methods take the same arguments as those of its parent
class.
After you have created a password field, call its
setEchoChar(
char
)
method to obscure
input by replacing each input character with the specified character.
The following statements create a password field and set its echo character to “#”:
JPasswordField codePhrase = new JPasswordField(20);
codePhrase.setEchoChar('#');
Text Areas
Text areas
, editable text fields that can handle more than one line of input, are imple-
mented with the
JTextArea
class.
JTextArea
includes the following constructors:
JTextArea(
int
,
int
)
—A text area with the specified number of rows and
columns
n
JTextArea(
String
,
int
,
int
)—
A text area with the specified text, rows, and
columns
n