created 06/29/99

Programming Exercises

All these exercises can be done by thoughtfully modifying the example program of the chapter.


Exercise 1 — Guessing Game

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.

Click here to go back to the main menu.


Exercise 2 — Error Message

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.

Click here to go back to the main menu.


Exercise 3 — Echo Both Fields

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.

Click here to go back to the main menu.


Exercise 4 — Text Swap

Add a JButton to the GUI. Modify the program so that when the button is clicked, the Strings in the two JTextFields 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 an event from the button. When it gets one, it swaps whatever text is in the two fields.

Click here to go back to the main menu.