Technical Support
Discussion Forum
Online Training
Read About Java
Java In-Depth
Product Discounts
Membership Information

Java Cup Logo

JDC Home Page


Working Applet
Help and Hints
Source Code
Table of Contents
Online Training
shadowSearchFAQFeedback

LabeledChoice Help

Help is available for each task, or you can go straight to the LabeledChoice source code to see a solution.

Task 1

Create an Applet to hold one instance of LabeledChoice so you can test the component.

You need to create a class separate from your LabeledChoice class. You can call it LabeledChoiceTest. In this class, create an instance of LabeledChoice and add it to the container.

import java.awt.*;

public class LabeledChoiceTest extends java.applet.Applet {

    public void init() {
        LabeledChoice test = new LabeledChoice("Test");
        add(test);
    }
}

Task 2

Create class LabeledChoice as a subclass of FormElement.

public class LabeledChoice extends FormElement {
    ...
}

Task 3

In class LabeledChoice, create a left-justified Label and a Choice to the right. Make the Choice fill the entire remaining width of the Panel.

You have to create a constructor to initialize the components needed by your compound component, and to add them to the current Container. In this case, the Container is a Panel because FormElement subclasses Panel:

class LabeledChoice extends FormElement {
    protected Choice   choice;
    protected String   label = "Payment Method";

    public LabeledChoice(String label) {
        this.label = label;
        setLayout(new BorderLayout(5,0)); // hgap of 5, no vgap

        choice = new Choice();
        // add a few items to the Choice
        choice.addItem("American Express");
        choice.addItem("Master Card");
        choice.addItem("Visa");
        choice.addItem("Cash");
        choice.addItem("Check");

        // add the label and the Choice to the FormElement
        add("West", new Label(label, Label.LEFT));
        add("Center", choice);
    }
    ...
}

label and choice are instance variables so that other methods in this class will have access to them.

Task 4

Implement the method getContents of FormElement to return the Label and the contents of the LabeledChoice.

The visible item of Choice is the currently selected item (there is no such thing as an empty Choice

public String getContents() {
    return label + "    " + choice.getSelectedItem();
}