Experiments in Java


Experiments for Session G3: Java's AWT, Continued

Name: ________________
ID:_______________

Experiment G3.1: The AWT, reviewed

Required file:

Step 1. Make a copy of HelpfulHelloGUI.java. Compile and execute it. Describe what the application does.


 
 
 
 
 
 

Step 2. Change the line that reads

    help = new Button("Help");

to one that reads

    help = new Button("?");

What effect do you expect this change to have?


 
 
 

After recording your answer, recompile and execute the modified program to confirm that answer. You may also want to read the notes on this problem.

Step 3. Keeping the change from the previous step, update the line that reads

   else if (command.equals("Help")) 

to one that reads

   else if (command.equals(help.getLabel())

What effect do you expect this second change to have?


 
 
 

After recording your answer, recompile and execute the modified program to confirm that answer. You may also want to read the notes on this problem.

Step 4. Change the text of the help button back to Help. What changes would you need to make to HelpfulHelloGUI.java so that the help message would be ``Please click on the quit button to exit''?


 
 
 
 
 
 

Step 5. Update the line that reads

      out.setText("Click quit!");

to one that reads

      out.setText("Please click on the quit button to exit");

What effect do you expect this change to have when the user clicks on the Help button?


 
 
 

After recording your answer, recompile and execute the modified program to confirm that answer. You may also want to read the notes on this problem.

Step 6. As you may have noted, the label for the help message isn't big enough. We might guess that repacking the frame might do it. Update the appropriate portion of actionPerformed to read

      out.setText("Please click on the quit button to exit");
      gui.pack();

Does this make any difference?


 
 
 

Step 7. As you may have noted, the addition of the line that reads

      gui.pack();

does not seem to have made a difference. This is because the layout manager only looks at the size of things once, when they're added to the frame. What we need to do is re-add the output label so that the layout manager notices the new size. You do this with a variant of the add command, which takes a second parameter giving the position of the added component. Since we want the label to stay at the beginning, we use

      out.setText("Please click on the quit button to exit");
      gui.add(out,0);
      gui.pack();

Make this change. Does it make any difference to how HelpfulHelloGUI acts? If so, describe the difference.


 
 
 

After recording your answer, you may wish to look at the notes on this problem.

Step 8. As you saw in the previous step, you can choose where to add components. Suppose we had used

      gui.add(out,2);

instead of

      gui.add(out,0);

What do you expect the differences will be in what happens when the user clicks on the Help button?


 
 
 

Step 9. Recompile and execute HelpfulHelloGUI and explain the differences.


 
 
 
 
 
 

After recording you answer, you may wish to look at the notes on this problem.

Step 10. Suppose we had instead used

      gui.add(out,10);

What do you expect the differences will be in what happens when the user clicks on the Help button?


 
 
 
 
 
 

After recording you answer, you may wish to look at the notes on this problem.

Step 11. The AWT also permits you to remove components with the remove method. What do you expect the effect of the following lines to be?

      out.setText("Please click on the quit button to exit");
      gui.add(out,0);
      gui.remove(help);
      gui.pack();


 
 
 
 
 
 

Experiment G3.2: Getting input from the user

Required file:

Step 1. Make a copy of GreetGUI.java. Compile and execute it. Describe what the application does.


 
 
 
 
 
 

If you can't figure out how to quit the program, look at the notes on this problem.

Step 2. As you may have observed in step 1, there are some extra spaces in the input field that interfere with data entry. This is because in GreetGUI, the instruction to create the input field reads

    userName = new TextField("          ");

What do you expect to happen if you replace this by the following line?

    userName = new TextField("");


 
 
 
 
 
 

Confirm your answer by making the change, recompiling GreetGUI, and executing GreetGUI. After you have done so, restore the line that reads

    userName = new TextField("          ");

Step 3. As you may have observed in step 2, deleting all the spaces results in insufficient space for data entry. How can we balance the need for an empty field and the need for an initial size? One strategy is to clear the field at an appropriate time.

How might you clear the contents of text field userName?


 
 
 

Step 4. The appropriate time to clear the field is after you've done the layout because once the layout has been done, the space for the field is fixed. Try adding the following lines to GreetGUI.java directly after gui.pack().

    // Clear the field.
    userName.setText("");

What effect do you expect this change to have?


 
 
 

Confirm your answer by making the change, recompiling GreetGUI, and executing GreetGUI.

Step 5. What do you expect to happen when you run GreetGUI and enter a particularly long name, such as John Doe, the Everyman?


 
 
 

Confirm your answer by executing GreetGUI and entering a long name. Does expanding the window make any difference?

Step 6. How do we recover from the previous problem? We'd like to expand the size of the out label. One possibility is to add it to the frame again. (Each object can only appear once in the frame.)

Update the actionPerformed method to read

  /** React to a click on the button. */
  public void actionPerformed(ActionEvent evt) {
    // Update the output
    out.setText("Hi there " + userName.getText() +
                ", welcome to this program.");
    // The size may have changed, so add it again.
    gui.add(out);
  } // actionPerformed(ActionEvent)

Does this have any effect? Does expanding the window make any difference?


 
 
 
 
 
 

Step 7. As you may have observed in the previous step, by re-adding out, we were able to expand the size it is given. Unfortunately, we did not expand the window, too. (This may be a good thing; some users will find it disconcerting if windows keep changing sizes.) Can we also expand the window? Yes! With the pack method.

Update the actionPerformed method to read

  /** React to a click on the button. */
  public void actionPerformed(ActionEvent evt) {
    // Update the output
    out.setText("Hi there " + userName.getText() +
                ", welcome to this program.");
    // The size may have changed, so add it again.
    gui.add(out);
    // And then redraw the frame (perhaps enlarging it).
    gui.pack();
  } // actionPerformed(ActionEvent)

Does this have the intended effect? What is your aesthetic judgment of the results?


 
 
 
 
 
 

Experiment G3.3: String manipulation

Required files:

In this experiment, you'll consider a technique for having different classes (or, more precisely, different objects) listen to different buttons. The technique we use in this experiment is to attach a FieldModifier to each button.

Step 1. Read and explain the code for FieldModifier.java.


import java.awt.*;
import java.awt.event.*;
import StringModifier;

/**
 * Objects that listen to buttons and, in response, modify a
 * TextField in an AWT application.  You need one FieldModifier
 * per type of modification per field.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of February 1999
 */
public class FieldModifier
  implements ActionListener
{
  // +-----------------------------------------------------------
  // | Fields |
  // +--------+
  
  // No, this doesn't modify these kinds of fields; it modifies
  // the text in a TextField in an AWT.
  
  /** The field to modify. */
  protected TextField field;
  
  /** The string modifier used to modify its contents. */
  protected StringModifier stringmod;
 
  // +--------------+---------------------------------------------
  // | Constructors |
  // +--------------+
  
  /** 
   * Build a new FieldModifier that can modify a particular field
   * using a particular modifier.  
   */
  public FieldModifier(TextField field, StringModifier stringmod) {
    this.field = field;
    this.stringmod = stringmod;
  } // FieldModifier(TextField,StringModifier)
  
  
  // +---------+-------------------------------------------------
  // | Methods |
  // +---------+
  
  /**
   * When asked to perform an action, modify the field.  Used a
   * ``long form'' for the code, which could be expressed more
   * succinctly.
   */
  public void actionPerformed(ActionEvent evt) {
    // Get the contents of the field.
    String str = field.getText();
    // Update the string
    str = stringmod.modify(str);
    // And replace the contents of the field.
    field.setText(str);
  } // actionPerformed(ActionEvent)
} // class FieldModifier



 
 
 
 
 
 

Step 2. Make a copy of all the required files. Compile all the files and then execute StringFun. Summarize what the program does.


 
 
 
 
 
 

Step 3. As you may have noted, when we create a FieldModifier, we supply two parameters to the constructor, as in

    upperCase.addActionListener(
      new FieldModifier(info, new MakeUpperCase()));

The first parameter is the field to modify when the button is clicked (when the FieldModifier is activated); the second is a StringModifier that will be used to modify the field. What do you expect to happen if we change new MakeUpperCase() to new Quote()? (You should also add an appropriate import statement.)


 
 
 
 
 
 

Confirm your answer by making the change, recompiling, and executing. Once you've confirmed your answer, restore the code.

Step 4. What changes do you expect to have to make in order to add a second button that puts quotes around the string?


 
 
 
 
 
 

Step 5. Make the changes to add this new Quote button. The changes are as follows.

A. Add an import statement of the form

import Quote;

B. Add a new field called quote, using

  /** The ``put quotes around'' button. */
  protected Button quote;

C. In the constructor for StringFun, build that button with

    quote = new Button("Put in quotes");

D. In the constructor for StringFun, add a listener for that button with

    quote.addActionListener(
      new FieldModifier(info,
                        new Quote()));

E. Add that button to the interface with

    gui.add(quote);

After making the changes, confirm that the revised StringFun supports both conversion to uppercase and quoting.

Step 6. Create a MakeLowerCase class. You may want to refer to the code for MakeUpperCase.java when doing so. Summarize the class here.


 
 
 
 
 
 
 
 
 
 
 
 
 
 

Step 7. Update StringFun to include a button that converts the field to lowercase. Summarize the changes here.


 
 
 
 
 
 

Step 8. Update StringFun to include a button that uses the FirstWord class. What does that class (and therefore that button) do? Note that you should try various strings, such as ``Hello'' (just one word), ``Hello World'' (two words), and ``Hello Cool World'' (three words).


 
 
 

Step 9. You may have noted that FirstWord uses the substring method provided by the String class. What are the parameters to that method? (You may need to refer to the Java documentation.)


 
 
 

Step 10. You may have noted that FirstWord uses one form of the indexOf method from the String class. What other forms are there?


 
 
 

Experiment G3.4: A simple calculator

Required file:

Step 1. Make a copy of SimpleCalc.java. Compile and execute it. Enter the values 2 and 3 and click on the = button. Enter the values 5 and 10 and click on the = button. Summarize the appearance and features of this application.


 
 
 
 
 
 

If you can't figure out how to quit the program, look at the notes on this problem.

Step 2. What do you expect to happen if you enter the values ``two'' and ``three'' and click on the = button?


 
 
 

Step 3. What does happen if you enter the values ``two'' and ``three'' and click on the = button?


 
 
 

Step 4. Read through the code for SimpleCalc.java and identify the part of the code that does this error checking. Summarize the design of that code.


 
 
 
 
 
 

Experiment G3.5: Supporting real numbers

Required file:

Before you begin, if you have not already done so, make a fresh copy of SimpleCalc.java and compile it.

Step 1. What do you expect will happen if you try to add 1.5 and 2 with SimpleCalc?


 
 
 

Step 3. What happens if you try to add 1.5 and 2 with SimpleCalc?


 
 
 

Step 4. As you may have observed in the previous step, SimpleCalc is only designed to input and add integers. In order to add 1.5 and 2, we would have to expand SimpleCalc to input and add real numbers (either floats or doubles). Read through the code for SimpleCalc.java and note the places in which SimpleCalc makes assumptions that it's working with integers.


 
 
 
 
 
 

After doing so, you may wish to refer to the notes on this problem.

Step 5. Update SimpleCalc so that it can accept real numbers (i.e., doubles) as input. Summarize the changes you've made.


 
 
 
 
 
 

Experiment G3.6: Adding a quit button

Note: You may have completed a similar experiment in the previous laboratory. This experiment is intended to help reinforce some of the AWT concepts.

Required file:

Step 1. Make a fresh copy of SimpleCalc.java. Compile and execute it to ensure that it still works.

Step 2. Read through the code for SimpleCalc.java and make notes on what lines you'd have to add (and where) in order to add a Quit button.


 
 
 
 
 
 

Step 3. Add a Quit button to SimpleCalc. You will need to add a new field, quit.

  /** The button used to tell it to quit. */
  protected Button quit;

You will also need to add code to create the button.

    // Create the quit button.
    quit = new Button("Quit");
    quit.addActionListener(this);

Finally, you will have to add it to the frame.

    gui.add(quit);

Compile the modified SimpleCalc and correct any compiler errors you encounter.

Step 4. What do you expect will happen when someone clicks on the Quit button?


 
 
 

Step 5. Run the modified SimpleCalc and determine what happens when someone clicks on the Quit button. Explain why.


 
 
 

Step 6. Update the actionPerformed method to quit the program.

  /** Quit when the user clicks on the quit button. */
  public void actionPerformed(ActionEvent evt) {
    gui.dispose();
    System.exit(0);
  } // actionPerformed(ActionEvent)

Recompile SimpleCalc

Step 7. What do you expect will now happen when someone clicks on the Quit button?


 
 
 

After entering your answer, run the modified SimpleCalc to verify that answer.

Step 8. What do you expect will now happen when someone clicks on the = button?


 
 
 
 
 
 

Step 9. Run the modified SimpleCalc and determine what happens when someone clicks on the = button. Explain why.


 
 
 
 
 
 


Copyright (c) 1998 Samuel A. Rebelsky. All rights reserved.

Source text last modified Tue Oct 26 12:31:27 1999.

This page generated on Tue Oct 26 15:37:36 1999 by Siteweaver.

Contact our webmaster at rebelsky@math.grin.edu