Java Reference
In-Depth Information
There are also constructors that take an additional
String
argument that specifies an initial
string to display in the text component.
SYNTAX
JTextField
Name_of_Text_Field
=
new
JTextField(
Initial_String
,
Characters_Per_Line
);
JTextArea
Name_of_Text_Area
=
new
JTextArea(
Initial_String
,
Number_of_Lines
,
Characters_Per_Line
);
EXAMPLES
JTextField name =
new
JTextField("Enter name here.", 30);
JTextArea someText =
new
JTextArea("Enter story here.\nClick button.", 10, 30);
Number of Characters per Line
The number of characters per line (given as an argument to constructors for
JTextField
or
JTextArea
) is not the number of just any characters. The number gives the number of em
spaces in the line. An
em space
is the space needed to hold one uppercase letter M, which
is the widest letter in the alphabet. So a line that is specified to hold 20 characters will always
be able to hold at least 20 characters and will almost always hold more than 20 characters.
Scroll Bars
Scroll bars for text areas and text fields are discussed in Chapter 18. They are a nice touch,
but until you reach Chapter 18, your GUI programs will work fine without them.
TIP: Labeling a Text Field
Sometimes you want to label a text field. For example, suppose the GUI asks for a
name and a credit card number and expects the user to enter these in two text fields. In
this case, the GUI needs to label the two text fields so that the user knows in which
field to type the name and in which field to type the credit card number. You can use
an object of the class
JLabel
to label a text field or any other component in a Swing
GUI. Simply place the label and text field in a
JPanel
and treat the
JPanel
as a single
component. For example, we did this with the text field
name
in Display 17.17.
■