Java Reference
In-Depth Information
Or, if you want to work with all elements as an array, use either
public Object[] toArray()
or
public void copyInto(Object anArray[])
. You can also check for the existence of an element
within a model with methods such as
public boolean contains(Object element)
,
public int
indexOf(Object element)
,
public int indexOf(Object element, int index)
,
public int
lastIndexOf(Object element)
, and
public int lastIndexOf(Object element, int index)
.
Tip
Once you're finished adding elements to the data model, it's a good idea to trim its length with
public void
trimToSize()
. This removes any extra preallocated space within the internal data structure. In addition, if you
know the size of the data model in advance, you can call
public void ensureCapacity(int minCapacity)
to
preallocate space. Both of these methods work only with
DefaultListModel
.
■
ComboBoxModel Interface
The
ComboBoxModel
interface extends the
ListModel
interface. The key reason for this extension
is that the classes that implement the
ComboBoxModel
interface need to manage the selected
item internally through a
selectedItem
property, as shown by the interface definition.
public interface ComboBoxModel extends ListModel {
// Properties
public Object getSelectedItem();
public void setSelectedItem(Object anItem);
}
MutableComboBoxModel Interface
In addition to the
ComboBoxModel
interface, another data model interface,
MutableComboBoxModel
, extends
ComboBoxModel
to make methods available to modify the
data model.
public interface MutableComboBoxModel extends ComboBoxModel {
// Other methods
public void addElement(Object obj);
public void insertElementAt(Object obj, int index);
public void removeElement(Object obj);
public void removeElementAt(int index);
}
The
JComboBox
component uses an implementation of this interface by default.
DefaultComboBoxModel Class
The
DefaultComboBoxModel
class extends the
AbstractListModel
class to provide an appropriate
data model for the
JComboBox
. Because of this extension, it inherits the managing of the
ListDataListener
list.