Java Reference
In-Depth Information
■
Note
The
BasicDirectoryModel
class is another
ListModel
implementation. This implementation is
used by the file chooser component,
JFileChooser
, as described in Chapter 9.
The actual
ListModel
interface is rather simple. It provides for management of a
ListDataListener
, and it accesses the size of a particular element of the model.
public interface ListModel {
// Properties
public int getSize();
// Listeners
public void addListDataListener(ListDataListener l);
public void removeListDataListener(ListDataListener l);
// Other methods
public Object getElementAt(int index);
}
AbstractListModel Class
The
AbstractListModel
class provides a partial implementation of the
ListModel
interface. You
need to provide only the data structure and the data. The class provides for the list management
of
ListDataListener
objects and the framework for notification of those listeners when the
data changes. You can also get the list of listeners by using the
public ListDataListener[ ]
getListDataListeners()
method. When you modify the data model, you must then call the
appropriate method of
AbstractListModel
to notify the listening
ListDataListener
objects:
•
protected void fireIntervalAdded(Object source, int index0, int index1)
: To be
called after adding a contiguous range of values to the list.
•
protected void fireIntervalRemoved(Object source, int index0, int index1)
: To be
called after removing a contiguous range of values from the list.
•
protected void fireContentsChanged(Object source, int index0, int index1)
: To be
called if the modified range wasn't contiguous for insertion, removal, or both.
■
Note
The ranges specified by the
fire
XXX
()
methods of
AbstractListModel
are closed intervals. This
simply means that the indices are the endpoints of the range modified. There's no implied order for the
indices;
index0
, for example, doesn't need to be less than
index1
. The only requirement is that the methods
be called after the data model has changed.
If you have your data in an existing data structure, you need to convert it into a form that
one of the Swing components understands or implement the
ListModel
interface yourself. As
you'll see, an array or
Vector
is directly supported by
JList
and
JComboBox
. You can also wrap
your data structure into an
AbstractListModel
. For instance, if your initial data structure is an