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

List Help

Help is available for each task, or you can go straight to the List Source code, which is one particular solution.

Task 1

Create an applet called ListTest. Define an array of strings called items that contains strings you want displayed in a List. Add a new instance of MyList (with arguments "5,items").

public class ListTest extends java.applet.Applet {
    public void init() {
        // define elements to display in List
        String[] items = {
            "Red", "Orange", "Yellow",
            "Green", "Blue","Indigo", "Violet" };
        // define and create new MyList
        // showing 5 elements at once.
        MyList m = new MyList(5, items);
        // add to applet to display
        add(m);
    }
}

Task 2

Define class MyList as a subclass of List that accepts the number of items to display, and a list of String objects as the elements of the List.

You will find this object generally useful. The constructor simply adds each element of the String array passed in via addItem.

class MyList extends List {

    public MyList(int n, String[] elements) {
        super(n, false);  // no multiple selections
        for (int i=0; i<elements.length; i++) {
            addItem(elements[i]);
        }
    }
}

The super call invokes the List constructor with two arguments. The first argument is an int specifying how many rows of the list to display at once. The second argument is a boolean specifying whether to allow multiple selections (true) or not (false).