newsguy said:
Hi all;
I'm having a problem setting a combo box model. I have one that works:
stateComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
"AR Arkansas", "AK Alaska" ,ect...}))
Now what I would like is to have an array with just certain states in it,
that would be customizable by the user. But my code :
stateComboBox.setModel.setModel(states[]);
Doesn't work. I know there's a simple solution but what is it?
Thanks for your time.
Willie
Dunno if this is immediately relevant, but I thought I'd put it out here
anyway.
The only difference between a Swing ListModel and a Swing ComboBoxModel
is the concept of a selected item.
Here is a wrapper for a ListModel that implements a ComboBoxModel. This
means that you can use whatever implementation of ListModel that you
prefer to provide a ComboBoxModel.
import javax.swing.AbstractListModel;
import javax.swing.ListModel;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListDataEvent;
public class ListComboBoxModel
extends AbstractListModel
implements ComboBoxModel {
private ListModel _list;
private Object _selected = null;
/** Creates a new instance of ListComboBoxModel */
public ListComboBoxModel(ListModel list) {
_list = list;
_list.addListDataListener(new MyListener());
}
public Object getElementAt(int index) {
return _list.getElementAt(index);
}
public Object getSelectedItem() {
return _selected;
}
public int getSize() {
return _list.getSize();
}
public void setSelectedItem(Object anItem) {
if (_selected != null) {
fireContentsChanged(this, 0, getSize());
}
_selected = anItem;
if (_selected != null) {
fireContentsChanged(this, 0, getSize());
}
}
private class MyListener implements ListDataListener {
public void contentsChanged(ListDataEvent e) {
fireContentsChanged(
ListComboBoxModel.this,
e.getIndex0(),
e.getIndex1()
);
}
public void intervalAdded(ListDataEvent e) {
fireIntervalAdded(
ListComboBoxModel.this,
e.getIndex0(),
e.getIndex1()
);
}
public void intervalRemoved(ListDataEvent e) {
fireIntervalRemoved(
ListComboBoxModel.this,
e.getIndex0(),
e.getIndex1()
);
}
}
}
Rogan