Title: Components
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

AWT Components

So far we have looked at the Label class, Button, TextField and TextArea classes. In this section, we are going to look at classes that are related to making choices.

Checkbox

1. A Checkbox has a name and a state (true or false). If the state is true, the Checkbox has a check in it. There are 2 constructors for the Checkbox that are useful here:
// Create a named Checkbox with a default state of false
Checkbox(String name);
// Create a named Checkbox with a specified state
Checkbox(String name, boolean state);
2. If you want to read back the state of the Checkbox,
call the getState() method.
3. If you want to change the state of the Checkbox,
call setState(boolean newstate).

Radio Boxes

I'm not thrilled with this, but the Checkbox class also implements Radio buttons. The way this happens is by using different constructors.

1. A Radio button is sort of like a set of Checkboxes with the property that no more than one in the set can be selected at a time. In fact if a new Radio button is selected out of the set, then we automatically expect any other selected button to be deselected.
2. To create a Radio Box, you first create a CheckboxGroup. You then pass this CheckboxGroup to all of the Checkboxes that go with the Radio Box group. For example, the following code would create radio buttons for choosing male or female:
CheckboxGroup gender = new CheckboxGroup();
Checkbox male = new Checkbox("Male", gender, false);
Checkbox female = new Checkbox("Female", gender, false);
3. Note that in the above example, we are using a different constructor for Checkbox that includes a CheckboxGroup parameter. The user will see the expected radio button out of this example.
4. Check out the generation set of radio buttons below. Of course, you can still use the getState and setState methods in the radio button case.
5. From the CheckboxGroup, you can also call the getSelectedCheckbox to return the selected Checkbox in a radio button group. You can then use the getLabel() method to return the associated text for the selected radio button.

AWT Selection Components

Check.java


import java.awt.*;
import java.awt.event.*; // New Import for Events

public class Check extends java.applet.Applet
    implements ActionListener
{
   TextArea toutput = new TextArea(6,40);

   // Regular Check Boxes
   Checkbox chkCar = new Checkbox("Own Car?");
   Checkbox chkStudent = new Checkbox("Student at WCC?");

   // Radio Button Classes
   CheckboxGroup generation = new CheckboxGroup();
   Checkbox[] genChk= new Checkbox[5];

   String endline;
   String genName[] = {"Senior", "Boomer", "X", "Adolescent", "Infant"};

   public void init() {
        // Default the following checkbox to checked
        chkStudent.setState(true);
        add(chkCar);
        add(chkStudent);
        add(new Label("**********************Checkbox**Radio*****************************"));

        for (int i=0; i < genName.length; i++)
        {
            genChk[i] = new Checkbox(genName[i], generation, false);
            add(genChk[i]);
        }
        // Set default radio button selection
        genChk[2].setState(true); // Set generation X by default



        add(new Label("*****************************************************************"));
        Button b = new Button(
            "--         Click here to get something done       --");
        add(b);
        add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {
        String str;
        int[] indexes;
        String[] strs;

        toutput.append("**********************************" + endline);
        toutput.append("Student at WCC? " +
            chkStudent.getState()  + endline);
        toutput.append("Own Car? " +
            chkCar.getState()  + endline);

        for (int i=0; i < genChk.length; i++)
            if (genChk[i].getState())
            {
                toutput.append("generation: " + genName[i] + endline);
                // Could put a break here and get the same answer
            }
        // Another way to access the CheckBox group:
        Checkbox selected = generation.getSelectedCheckbox();
        toutput.append("Label of selected Checkbox: " +
                selected.getLabel()  + endline);

       }


  public static void main(String[] args) {
    Check applet = new Check();
    Frame aFrame = new Frame("Check");

    aFrame.add(applet);
    aFrame.setSize(380,380);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}



Click on Check boxes or Radio Buttons

Click on Button to see the current states

Selection.java

There are also 2 useful classes that give you selection lists.

1. The Choice class gives you a Drop-Down Selection box
2. The List class gives you a list of selections that you can make. There is a method you can call to allow the List box to allow multiple selections:
setMultipleMode(true);
3. The methods available for both the Choice and the List are:
  - add(String name) - add a new entry to the list
  - remove(String name) - remove an entry. This throws an exception if the entry doesn't exist.
  - getItemCount( ) - return number of entries in the list
  - String getSelectedItem( ) - return the currently selected item
  - int getSelectedIndex( ) - return the currently selected index
4. If your List has the MultipleMode flag set, then you can also call
  - int[] getSelectedIndexes( )- return an array of selected indexes
  - String[] getSelectedItems( ) - return an array of selected entries


import java.awt.*;
import java.awt.event.*; // New Import for Events

public class Selection extends java.applet.Applet
    implements ActionListener
{
   TextArea toutput = new TextArea(4,40);
   TextField tadd = new TextField(40);

   // Dropdown Selection Box
   Choice myChoice = new Choice();

   // Selection List allowing only one selection
   List myList = new List();

   // Selection List allowing multiple selections
   List myMultList = new List();

   String endline;
   String strlist[] ={"zero", "one", "two", "three", "four", "five"};

   public void init() {
        add(new Label("**********************Choice**************************************"));
        add (myChoice);
        for (int i = 0; i < strlist.length; i++)
            myChoice.add(strlist[i]);

        add(new Label("**********************List****************************************"));
        add (myList);
        for (int i = 0; i < strlist.length; i++)
            myList.add(strlist[i]);

        add(new Label("**********************List**Multiple Selection********************"));
        add (myMultList);
        // Make this list allow multiple selections
        myMultList.setMultipleMode(true);
        for (int i = 0; i < strlist.length; i++)
            myMultList.add(strlist[i]);

        add(new Label("********String to add to lists (- in front will remove)***********"));
        add(tadd);
        Button b = new Button(
            "--         Click here to get something done       --");
        add(b);
        add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {
        String str;
        int[] indexes;
        String[] strs;

        toutput.append("**********************************" + endline);
        toutput.append("myChoice: total: "   + myChoice.getItemCount() + endline+
                        "      selected index = " + myChoice.getSelectedIndex() +
                        " selected item = "  + myChoice.getSelectedItem() + endline);

        toutput.append("myList: total: "   + myList.getItemCount() + endline+
                        "      selected index = " + myList.getSelectedIndex() +
                        " selected item = "  + myList.getSelectedItem() + endline);

        indexes = myMultList.getSelectedIndexes();
        strs = myMultList.getSelectedItems();
        toutput.append("myMultList: "+ endline);
        for (int i = 0; i < indexes.length; i++)
        {
           toutput.append("   index = " + indexes[i] +
                          " item = " + strs[i] + endline);
        }

        str = tadd.getText();
        str = str.trim();

        // If any string is found in the tadd TextField, we will either try
        // to add a string to the choice, list and multiple list components
        // or remove a string.  Removing happens if the string starts with a "-"

        if (str.length() > 0)
        {
            if (str.charAt(0) != '-')
                {
                    myChoice.add(str);
                    myList.add(str);
                    myMultList.add(str);
                    toutput.append("Successfully added " + str +
                        " to lists " + endline);

                }
             else
                {
                    // Remove from lists
                    try
                    {
                        str = str.substring(1); // remove - sign
                        myChoice.remove(str);
                        myList.remove(str);
                        myMultList.remove(str);
                        toutput.append("Successfully removed " + str +
                            " from lists " + endline);
                    }
                    catch (IllegalArgumentException e)
                    {
                        toutput.append("Exception: " + e + endline);
                    }

                }
        }
       }


  public static void main(String[] args) {
    Selection applet = new Selection();
    Frame aFrame = new Frame("Selection");

    aFrame.add(applet);
    aFrame.setSize(380,480);
    // Normally the following call comes from the Browser
    applet.init();

    aFrame.setVisible(true);
  } // end of main
}




Click on selections.

Click on multiple entries in the Multiple List

Click on Button to see current state

Enter name or -name in TextField and Click button to add/remove items

Exercises:

Job Applicaton Form

Create a job application form applet that utilizes most of the Components we have covered so far. When you click an Apply button, the results of the application form should be written to System.out.println. Your applet should demonstrate at least the following Components:

1. Textfield
2. List
3. Choice
4. Checkbox (both flavors : radiobutton type, versus checkbox type)
5. Label

You can put any fields you want in your application, but here are some recommendations:

You could have the following textfields:
Name, address, Social Security number

For a List box, you might have your applicant pick from a list of skills that you provide. For example,
C++, Java, Html, MFC, Visual Basic, Oracle, etc.

For a choice box, you might have a list of states. You might only want to put in a few of the local states. I.e.:
Michigan, Indiana, Ohio, Wisconsin, Illinois

For a Checkbox (non-radio type), you could choose something like:
Married, Veteran, Own Car

For a radio button you could choose,
Sex: Male/Female , Eye Color: Blue/Brown/Green/Other

Use the Label component to properly label the input fields of your application.

Calculator Example

Create a Command Line Form Based Calculator Program and an Applet Program. These 2 programs should be almost the same, but not identical --- in otherwords, I want only Applet code in the Applet and only Form related code in the Command Line Program.

Your programs should at least implement the first 2 items in the following list. The last 2 items are for an extra challenge.
- Your programs provide simple calculator functionality. Your program should have the name Calculator. You only need to handle 10 digit buttons (0,1, ... 9), the "+" button, the "=" button a clear button and a text field for the result. Don't worry about the button layouts for now. We will deal with that later.
- Add additional buttons for multiply and divide. Don't let a user divide by zero and blow up your calculator
- Add additional buttons for sin, cos, tan. You can find out about these functions in the language Math class. You might want to have some option to select between degrees or radians for the input angle.
- Add a choice drop-down box for storing intermediate results. You might want a button to add an intermediate result to your drop-down list, and perhaps some other button to delete one or more intermediate results.

Last Updated: December 6, 2002 10:09 AM