Java Reference
In-Depth Information
Self-Test Exercises
(continued)
34.
★
How can you modify the program in Display 17.16 so that when the
Blue
menu item is clicked, all three colors are shown? The
Red
and
White
choices
remain the same. (Remember the menu items may be clicked in any order, so
the
Blue
menu item can be the first or second item clicked.)
35.
★
Rewrite the Swing GUI in Display 17.16 so that there is only one action lis-
tener inner class. The inner class constructor will have two parameters, one for a
panel and one for a color.
17.5
Text Fields and Text Areas
Write your answers in the spaces provided.
COMMON INSTRUCTION FOR AN EXAMINATION
You have undoubtedly interacted with windowing systems that provide spaces for you to
enter text information such as your name, address, and credit card number. In this section,
we show you how to add these fields for text input and text output to your Swing GUIs.
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:
text field
JText-Field
private
JTextField name;
...
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, and if that is
desired, 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();