| Class 2 | Intermediate Java 30-IT-397 |  | 
List Models
- 
It is surprisingly difficult to add an item to a JList that already exists. 
You have to get into the guts of the JList, into the Model - View - Controller
design.
- 
The JList only displays data.  It does not actually store data. 
It knows how to get the data, though.
- 
It is the job of the ListModel to actually store the data.
- 
If you pass an Array or Vector of data to a JList, it creates a model for
you.
- 
But, if you need to perform more complex tasks, such as adding or removing
data dynamically, you'll need to develop your own model.
- 
The ListModel
interface has four methods that the JList uses to get data:
- 
public int getSize() returns the number of elements in the list.
- 
public Object getElementAt(int i) gets the ith element
from the model.
- 
public void addListDataListener(ListDataListener l) adds a ListDataListener
to the model.
- 
public void removeListDataListener(ListDataListener l) removes
the ListDataListener from the model.
- 
The JList uses these methods to count and retrieve the elements in the
model.  It can also add itself as a listener so that it can repaint
the list when items are added or removed.
- 
The use of the ListModel allows you to store the items any way you wish. 
You can store them in a more complex object than a Vector, perhaps add
some logic to the get methods as well.  This gives you the liberty
of complete flexibility.
The AbstractListModel
 
Created by:  Brandan Jones
December 17, 2001