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

Java Cup Logo

JDC Home Page


Top
Back
Next
Online Training
shadowSearchFAQFeedback

List

A List is a scrolling list box that allows you to select one or more items.



Multiple selections can be enabled by passing true as the second argument to the List constructor.

Corresponding source code:

import java.applet.*;
import java.awt.*;
public class ListWidget extends Applet {
    public void init()
    {
        String[] items={"Seattle", "Washington",
                        "New York", "Chicago", "Miami",
                        "San Jose", "Denver" };
        Selector s = new Selector(5, items);
        add(s);
    }
}

class Selector extends List {
    public Selector(int numItemsToDisplayAtOnce, String[] elements)
    {
        // create a list box that doesn't allow multiple selections
        super(numItemsToDisplayAtOnce, false);
        // add the list of elements to the list box
        for (int i=0; i<elements.length; i++) {
            addItem(elements[i]);
        }
    }
}

Methods:

  • public List(int rows, boolean multipleSelections)
    Creates a List showing the specified number of rows. If there are multipleSelections then multiple items from the List can be selected at once but not otherwise.
  • public void addItem(String item)
    Adds the String to the end of the item list.
  • public int getSelectedIndex()
    Which item is selected?
  • public String getSelectedItem()
    Which item is selected?
  • public void select(int index)
    Selects item at index.

Related exercises: