All these exercises can be done by thoughtfully modifying (hacking) the example program of the chapter.
Modify the Repeater
program so that
the user must enter a secret word into the top field.
After each entry, the bottom field either says
"correct" or "wrong!"
After three wrong guesses, exit the program.
You will need the equals()
method of class String
for this
program.
Modify the Repeater
program so that
when the user enters text into the bottom TextField
and hits enter, the text is replaced with an
error message such as "Enter text in the top field."
You will need to modify the actionPerformed( ActionEvent evt )
method so that it determines which text field has just generated
an action.
This can be done by using evt.getActionCommand()
,
which evaluates to the String
that the user just entered
(no matter in which field it was entered.)
Now use getText()
with the top box to see if the string in
that field is the same as the command in the ActionEvent
.
If so, copy it to the bottom field.
If not, write the error message.
Be sure to register an ActionListener
for each JTextField
.
Modify the Repeater
program so that
the user can enter text into either field.
The text will be repeated in the other field,
replacing whatever was there.
To do this you will need to use getActionCommand()
,
as in Exercise 2.
Add a Button to the GUI.
Modify the program so that when the button is clicked,
the Strings in the two JTextField
s are swapped;
ie. the top field gets what was in the bottom box and
the bottom field gets what was in the top.
The actionPerformed()
method
will listen for a Button event.
When it gets one, it swaps whatever text is in
the two fields.