Java Reference
In-Depth Information
ArrayList from the Collections framework, you can convert the data structure to a ListModel
with the following code:
final List arrayList = ...;
ListModel model = new AbstractListModel() {
public int getSize() {
return arrayList.size();
}
public Object getElementAt(int index) {
return arrayList.get(index);
}
}
The other option is to just pass the List into the Vector constructor, and then pass that
Vector into the JList constructor. Effectively, you've then done the same thing.
DefaultListModel Class
The DefaultListModel class provides a data structure for you to store the data internally in the form
of a Vector . You just need to add the data, because the class manages the ListDataListener list
for you.
First, you create the data structure with the no-argument constructor: DefaultListModel
model = new DefaultListModel() . Then you manipulate it. As shown in Table 13-1, the
DefaultListModel class has only two properties.
Table 13-1. DefaultListModel Properties
Property Name
Data Type
Access
empty
boolean
Read-only
size
int
Read-write
The DefaultListModel class provides all its operational methods through a series of public
methods. To add elements, use the following methods:
public void add(int index, Object element)
public void addElement(Object element)
public void insertElementAt(Object element, int index)
The addElement() method of DefaultListModel adds the element to the end of the data model.
To change elements, use these methods:
public Object set(int index, Object element)
public void setElementAt(Object element, int index)
And to remove elements, these methods are provided:
Search WWH ::




Custom Search