Java Reference
In-Depth Information
Note One case in which you may wish to provide your own model is when you need to support the presence of
the same item within the model multiple times. With the DefaultComboBoxModel , if you have two items in
the list whose equals() methods will return true , the model won't work properly.
If you really want to define your own model implementation, perhaps because you already
have the data in your own data structure, it works best to subclass the AbstractListModel and
implement the ComboBoxModel or MutableComboBoxModel interface methods. When subclassing
the AbstractListModel , you merely need to provide the data structure and the access into it.
Because the “selected item” part of the data model is maintained outside the primary data
structure, you need a place to store that, as well. The program source in Listing 13-2 demonstrates
one such implementation using an ArrayList as the data structure. The program includes a
main() method to demonstrate the use of the model within a JComboBox .
Listing 13-2. Using a Custom Data Model
import java.awt.*;
import javax.swing.*;
import java.util.Collection;
import java.util.ArrayList;
public class ArrayListComboBoxModel
extends AbstractListModel implements ComboBoxModel {
private Object selectedItem;
private ArrayList anArrayList;
public ArrayListComboBoxModel(ArrayList arrayList) {
anArrayList = arrayList;
}
public Object getSelectedItem() {
return selectedItem;
}
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
}
public int getSize() {
return anArrayList.size();
}
public Object getElementAt(int i) {
return anArrayList.get(i);
}
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("ArrayListComboBoxModel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
Search WWH ::




Custom Search