JList
The JList class displays a selection of a number of items, from which one or more may be selected. It is possible to pass an array of objects into the JList constructor, and it is usual to nest the list inside a JScrollPane:
String[] options = {"Red", "Green", "Blue"};
JList list = new JList(options);
panel.add(new JScrollPane(list));
The above should result in the following:
By default, the user is allowed to select multiple items in the list. If you want to ensure that only one item can be selected at a time use the setSelectionMode() method:
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
As you learned in Section 6, arrays are of a fixed size and therefore lack the flexibility of being able to dynamically contract or expand with new or removed items. To obtain the additional flexibility you can assign a ListModel object to your JList in order to provide the items to appear in the list[1]. ListModel is an interface which you can implement to provide the list data, although typically an easier way is to extend the Java supplied DefaultListModel class (which itself implements ListModel). In DemoUI define an inner class called ColourListModel as follows:
private class ColourListModel extends DefaultListModel {
private ArrayList<String> colours;
public ColourListModel() {
colours = new ArrayList<String>();
colours.add("Red");
colours.add("Green");
colours.add("Blue");
}
@Override
public Object getElementAt(int index) {
return colours.get(index);
}
@Override
public int getSize() {
return colours.size();
}
}
ColourListModeldoes not have to be an inner class, although it is common to make it part of the class which defines theJList- The constructor instantiates an
ArrayListofStringobjects and adds three strings to it - As a minimum, you need to override the following two methods:
getElementAt()- which requires the index number of the item in the list and returns it as anObjectgetSize()- which returns the total number of items in the list
You can now instantiate a ColourListModel object and pass it as the argument to the JList constructor:
ListModel model = new ColourListModel(); JList list = new JList(model);
If you need to programmatically select one of the items in the list as a default you can use the setSelectedIndex() method:
list.setSelectedIndex(0); // selects the first item
To obtain which item has been selected you can use either the getSelectedIndex() or getSelectedValue() methods:
int i = list.getSelectedIndex(); String s = (String) list.getSelectedValue(); // need to cast
Comments