List Models
Home ] Up ] List Boxes ] Scrolling Lists ] Combo Boxes ] [ List Models ] List Selections ] List Renderers ]

 

 

One problem with simple JLists is that, surprisingly, they have no support for dynamically adding or removing items from the list.  If you want to provide this kind of functionality, you must use a ListModel.

Interface ListModel

The JList class is implemented using a Model-View-Controller architecture.   The model for a JList stores the data for the display, and must implement the javax.swing.ListModel interface, which consists of the following methods:

Method Description
public void addListDataListener(
                 ListDataListener l)
Adds a listener to the list that's notified each time a change to the data model occurs.
public Object getElementAt(int index)
Returns the value at the specified index. 
public int getSize()
Returns the length of the list.
public void removeListDataListener(
                 ListDataListener l)
Removes a listener from the list that's notified each time a change to the data model occurs. 

The ListDataListener interface must be implemented by any class that wishes to receive indications of changes to the data in the ListModel.  The other two methods clearly allow one to determine the number of items in the list, and to obtain the element at a particular index in the list.  Notice that there is still no way to add or remove items using a pure list model.

Class AbstractListModel

The abstract class AbstractListModel implements the ListModel interface, but only implements support for the ListDataListener methods.  It is the superclass for a number of subclasses, and provides support for firing ListDataEvents.

Class DefaultListModel

The concrete class DefaultListModel extends AbstractListModel, and adds support for adding and removing items from the list model.  It provides a large number of methods, loosely basing many of them on the Vector class.  The most immediately relevant methods are:

Method Description
public void addElement(Object obj)
Adds the specified component to the end of this list. 
public Object get(int index)
Returns the element at the specified position in this list. 
public int getSize()
Returns the number of components in this list. 
public Object remove(int index)
Removes the element at the specified position in this list. Returns the element that was removed from the list. 
public void clear()
Removes all of the elements from this list. The list will be empty after this call returns (unless it throws an exception). 
 

This page was last modified on 02 October, 2007