Java Reference
In-Depth Information
Text Areas and Text Fields
A
text field
is an object of the class
JTextField
and is displayed as a field that allows
the user to enter a single line of text. In Display 17.17, the following creates a text field
named
name
in which the user will be asked to enter his or her name:
private
JTextField name;
text field
JTextField
...
name =
new
JTextField(NUMBER_OF_CHAR);
In Display 17.17 , the variable
name
is a private instance variable. The creation of the
JTextField
in the last of the previous lines takes place inside the class constructor. The
number
NUMBER_OF_CHAR
that is given as an argument to the
JTextField
constructor
specifies that the text field will have room for at least
NUMBER_OF_CHAR
characters to
be visible. The defined constant
NUMBER_OF_CHAR
is
30
, so the text field is guaranteed
to have room for at least
30
characters. You can type any number of characters into a
text field but only a limited number will be visible; in this case, you know that at least
30
characters will be visible.
A Swing GUI can read the text in a text field and so receive text input; if this is
desired, it can produce output by causing text to appear in the text field. The method
getText
returns the text written in the text field. For example, the following will set
a variable named
inputString
to whatever string is in the text field
name
at the time
that the
getText
method is invoked:
String inputString = name.getText();
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");
Display 17.17
A Text Field
(part 1 of 3)
1
import
javax.swing.JFrame;
2
import
javax.swing.JTextField;
3
import
javax.swing.JPanel;
4
import
javax.swing.JLabel;
5
import
javax.swing.JButton;
6
import
java.awt.GridLayout;
7
import
java.awt.BorderLayout;
8
import
java.awt.FlowLayout;
9
import
java.awt.Color;
10
import
java.awt.event.ActionListener;
11
import
java.awt.event.ActionEvent;
12
public class
TextFieldDemo
extends
JFrame
13
implements
ActionListener
14 {
15
public static final int
WIDTH = 400;
16
public static final int
HEIGHT = 200;