Class 2 |
Intermediate Java 30-IT-397 |
|
AbstractListModel, DefaultListModel
-
ListModel is an interface, which means you must provide an implementation
for each of the four methods.
-
But it is actually not that bad - Java provides a default implementation
for two of the methods for you in the AbstractListModel.
All you have to do is implement the getSize() and getElementAt(int
i) methods.
-
DefaultListModel
goes one step further. It is an implementation of ListModel that
allows you to dynamically add and remove elements.
-
Internally, DefaultListModel holds the items in a Vector.
-
The only trick is, you can't pass in a vector to a constructor. You
must use the empty constructor of the DefaultListModel, the only constructor
provided, and then add each element individually via the addElement(Object
o) method.
-
Let's rebuild our JList example with a DefaultListModel. Further,
let's add another JFrame that permits the user to add his or her own buildings
and definitions.
-
As an added bonus, let's get rid of the Array all together. Why use
that when we can just use the DefaultListModel? We can access this
directly for our purposes, just as the JList can.
Example

Created by: Brandan Jones
December 17, 2001