1 6 7 package swingwtx.swing; 8 9 import java.util.*; 10 11 public class DefaultComboBoxModel extends AbstractListModel implements MutableComboBoxModel { 12 13 protected Vector objects; 14 protected Object selectedObject; 15 16 public DefaultComboBoxModel() {objects = new Vector(); } 17 public DefaultComboBoxModel(Object items[]) { 18 19 objects = new Vector(items.length); 20 for (int i = 0; i < items.length; i++) { 21 objects.add(items[i]); 22 } 23 if ( objects.size() > 0 ) 24 selectedObject = objects.get(0); 25 } 26 27 public DefaultComboBoxModel(Vector v) { 28 objects = v; 29 if (objects.size() > 0) 30 selectedObject = objects.get(0); 31 } 32 33 public void setSelectedItem(Object anObject) { 34 if ((selectedObject != null && !selectedObject.equals( anObject )) || selectedObject == null && anObject != null) { 35 selectedObject = anObject; 36 fireContentsChanged(this, -1, -1); 37 } 38 } 39 40 public Object getSelectedItem() { 41 return selectedObject; 42 } 43 44 public int getSize() { 45 return objects.size(); 46 } 47 48 public Object getElementAt(int index) { 49 if (index >= 0 && index < objects.size()) 50 return objects.get(index); 51 else 52 return null; 53 } 54 55 public int getIndexOf(Object anObject) { 56 return objects.indexOf(anObject); 57 } 58 59 public void addElement(Object anObject) { 60 objects.add(anObject); 61 fireIntervalAdded(this,objects.size()-1, objects.size()-1); 62 if (objects.size() == 1 && selectedObject == null && anObject != null) 63 setSelectedItem( anObject ); 64 } 65 66 public void insertElementAt(Object anObject,int index) { 67 objects.insertElementAt(anObject,index); 68 fireIntervalAdded(this, index, index); 69 } 70 71 public void removeElementAt(int index) { 72 if (objects.get(index) == selectedObject) { 73 if (index == 0) 74 setSelectedItem(objects.size() == 1 ? null : objects.get( index + 1 ) ); 75 else 76 setSelectedItem(objects.get(index - 1 )); 77 } 78 79 objects.removeElementAt(index); 80 81 fireIntervalRemoved(this, index, index); 82 } 83 84 public void removeElement(Object anObject) { 85 objects.remove(anObject); 86 } 87 88 public void removeAllElements() { 89 if ( objects.size() > 0 ) { 90 int firstIndex = 0; 91 int lastIndex = objects.size() - 1; 92 objects.removeAllElements(); 93 selectedObject = null; 94 fireIntervalRemoved(this, firstIndex, lastIndex); 95 } 96 else 97 selectedObject = null; 98 } 99 } 100 101 | Popular Tags |