posted 24 years ago
A class implementing ListModel directly needs to keep track of any registered listeners and notify them of any changes. This is kind of a pain to write, and AbstractListModel does much of the work for you, so I suggest using it. You just have to add any desired methods to change the list contents, and make sure you call the appropriate fireXXX() method afterward to tell the AbstractListModel to notify listeners of the change just made. Here's a simple example:
<code><pre>class FooListModel extends AbstractListModel {
private Vector fooVector = new Vector();
// required to implement ListModel:
public Object getElementAt(int index) {
return ((String) fooVector.elementAt(index)).a;
}
// required to implement ListModel:
public int getSize() {
return fooVector.size();
}
// sample additional method allowing modification of list:
public void addFooAt(int index, foo newFoo) {
fooVector.add(index, newFoo);
fireIntervalAdded(this, index, index);
}
// add more methods as you wish
}
</pre></code>
Note that the Vector is contained within the FooListModel, and only accessible through the model's methods. This way we can guarantee that any time the Vector is modified, we can make sure we call the correct fireXXX() method to go with it. Incidentally I'd probably use an ArrayList rather than a Vector, but kept the Vector here for familiarity.
"I'm not back." - Bill Harding, Twister