Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks


How to Use Lists

The List(in the API reference documentation) class provides a scrollable area containing selectable text items (one per line). Lists can allow either multiple selections or just one selection at a time. Other components that allow users to choose from multiple selections are checkboxes (checkbox groups, in particular), choices, and menus.

Below is an applet that shows two lists. The first list (which lists Spanish numbers) allows multiple selections. The second (which lists Italian numbers) allows a maximum of one selection.

Below is the code that creates each list and handles events on the lists. (Here's the whole program.) Note that the e.arg data for action events is the name of the acted-on item (similar to the argument for action events on other components such as buttons and even menus). However, the e.arg data for other list events is the number of the acted-on item.

    //where instance variables are declared:
    TextArea output;
    List spanish, italian; 

    //where initialization occurs:

    //Build first list, which allows multiple selections.
    spanish = new List(4, true); //prefer 4 items visible
    spanish.addItem("uno");
    spanish.addItem("dos");
    spanish.addItem("tres");
    spanish.addItem("cuatro");
    spanish.addItem("cinco");
    spanish.addItem("seis");
    spanish.addItem("siete");

    //Build second list, which allows one selection at a time.
    italian = new List(); //Defaults to none visible, only one selectable
    italian.addItem("uno");
    italian.addItem("due");
    italian.addItem("tre");
    italian.addItem("quattro");
    italian.addItem("cinque");
    italian.addItem("sei");
    italian.addItem("sette");

. . .

public boolean handleEvent(Event e) {
    if (e.target instanceof List) {
        List list = (List)(e.target);
        String language = (list == spanish) ?
			  "Spanish" : "Italian";

	switch (e.id) {
	  case Event.ACTION_EVENT:
	    String string = (String)e.arg;
	    output.appendText("Action event occurred on \""
	    		      + string  + "\" in "
			      + language + ".\n");
	    break;
	  case Event.LIST_SELECT:
	    int sIndex = ((Integer)e.arg).intValue();
	    output.appendText("Select event occurred on item #"
	    		      + sIndex + " (\""
	    		      + list.getItem(sIndex)  + "\") in "
			      + language + ".\n");
	    break;
	  case Event.LIST_DESELECT:
	    int dIndex = ((Integer)e.arg).intValue();
	    output.appendText("Deselect event occurred on item #"
	    		      + dIndex + " (\""
	    		      + list.getItem(dIndex)  + "\") in "
			      + language + ".\n");
	}
    }
    return super.handleEvent(e);
}


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks