8.6 Using a Field | 397
A data entry field is an object of the class JTextField. For example, we would declare a
variable called inputFieldas follows:
JTextField inputField; // Declare a field for data entry
When creating a JLabelobject with new, we pass a string to the JLabelconstructor that
tells it what text to display in the label. When creating a JTextFieldobject, we provide the con-
structor with the size of the field. Here is an example of creating a JTextFieldobject and
assigning its address to the variable inputField:
inputField = new JTextField(6);
In this example, the object associated with inputFieldis specified to have space for typing
six characters within it. We can give a default value to the field by including a string as the
first argument to the constructor. For example,
inputField = new JTextField("Replace Me", 10);
would cause the JTextFieldobject to be created with space for ten characters, and initially
the words "Replace Me"would appear within the field.
The last step in creating a field is to add it to a content pane. Just as with a label, we use
the content pane’s addmethod. If our content pane is called dataEntryPane, then we would write
the following:
dataEntryPane.add(inputField);
When we call dataEntryFrame.setVisible(true), the frame appears on the screen with a
field for entering data. As you can see, creating a field is just as simple as creating a label.
There is one very important difference between a JLabeland a JTextField, however: The user
of the application cannot change the text written in a JLabel, but the user can change the text
in the JTextField.
In some of our examples, we’ve instantiated anonymous labels directly within the ar-
gument list of add. Java lets us do the same thing with a JTextField, but we should never do
so. Our purpose in adding a JTextFieldis to later access its contents for input data, so a
JTextFieldobject must have its address assigned to a variable to be useful.
Next, let’s look at how to get the data from the field after the user has entered it.
8.6 Using a Field
Just as a JLabelobject has methods such as setTextassociated with it, so a JTextFieldobject
also comes with a set of instance methods. One method that JTextFieldshares in common
with JLabelis setText. The setTextmethod replaces the current contents of a field with a string
that is passed to it. Here is an example of calling setText:
inputField.setText("Replace Me");