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

JobTitleList Help

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

Task 1

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

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

import java.awt.*;

public class JobTitleListTest extends java.applet.Applet {

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

Task 2

Create class JobTitleList as a subclass of FormElement.

public class JobTitleList extends FormElement {
    ...
}

Task 3

In class JobTitleList, create a centered Label and a List below. Set the List so that multiple selections are not allowed.

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 JobTitleList extends FormElement {
    protected List     list;
    protected String   label = "Job Title";

    public JobTitleList() {
        list = new List(5,false);
        // add a bunch of items to the list
        list.addItem("President");
        list.addItem("CEO/CFO");
        list.addItem("Vice President");
        list.addItem("Manager");
        list.addItem("CTO");
        list.addItem("Engineer");
        list.addItem("Designer");
        list.addItem("Marketing");
        list.addItem("Programmer");
        list.addItem("Consultant");
        list.addItem("Scientist");
        list.addItem("Support Staff");
        list.addItem("Slacker");
        list.addItem("Webmaster");

        // put the label above the List.
        setLayout(new BorderLayout());
        add("North", new Label(label, Label.CENTER));
        add("Center", list);
    }
    ...
}

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

Task 4

Implement the method isEmpty of FormElement to return true if the List has a selected element.

When a List has no selected element, getSelectedIndex returns -1.

public boolean isEmpty() {
    return list.getSelectedIndex() == -1;
}

Task 5

Implement the method getContents of FormElement to return the Label and the currently selected element of the List.

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