1 19 20 package org.netbeans.modules.dbschema.jdbcimpl.wizard; 21 22 import java.util.Comparator ; 23 import java.util.List ; 24 import java.util.ArrayList ; 25 import java.util.Collection ; 26 import java.util.Collections ; 27 28 import javax.swing.AbstractListModel ; 29 30 31 34 public class SortedListModel extends AbstractListModel 35 { 36 37 40 public static final Comparator DEFAULT_COMPARATOR = new Comparator () 41 { 42 public int compare(Object o1, Object o2) 43 { 44 if (o1 == null) 45 return -1; 46 47 if (o2 == null) 48 return 1; 49 50 return o1.toString().compareTo(o2.toString()); 51 } 52 53 public boolean equals(Object obj) 54 { 55 return obj == this; 56 } 57 }; 58 59 62 private List elements; 63 64 67 private Comparator comp = DEFAULT_COMPARATOR; 68 69 73 76 public SortedListModel() 77 { 78 elements = new ArrayList (); 79 } 80 81 84 public SortedListModel(Collection c) 85 { 86 elements = new ArrayList (c); 87 Collections.sort(elements, comp); 88 } 89 90 93 public SortedListModel(int initialCapacity) 94 { 95 elements = new ArrayList (initialCapacity); 96 } 97 98 101 public int getSize() 102 { 103 return elements.size(); 104 } 105 106 109 public Object getElementAt(int index) 110 { 111 return elements.get(index); 112 } 113 114 119 public Comparator getComparator() 120 { 121 return comp; 122 } 123 124 127 public void setComparator(Comparator newComp) 128 { 129 if (comp == newComp) 130 return; 131 132 comp = newComp; 133 Collections.sort(elements, comp); 134 135 int last = elements.size() - 1; 136 137 if (last >= 0) 138 super.fireContentsChanged(this, 0, last); 139 } 140 141 144 public boolean isEmpty() 145 { 146 return elements.isEmpty(); 147 } 148 149 152 public boolean contains(Object o) 153 { 154 return Collections.binarySearch(elements, o, getComparator()) >= 0; 155 } 156 157 160 public Object [] toArray() 161 { 162 return elements.toArray(); 163 } 164 165 168 public Object [] toArray(Object [] a) 169 { 170 return elements.toArray(a); 171 } 172 173 176 public int add(Object o) 177 { 178 int index = Collections.binarySearch(elements, o, getComparator()); 179 if (index < 0) 180 index = -index - 1; 181 182 elements.add(index, o); 183 fireIntervalAdded(this, index, index); 184 185 return index; 186 } 187 188 191 public int indexOf(Object o) 192 { 193 return Collections.binarySearch(elements, o, getComparator()); 194 } 195 196 199 public int remove(Object o) 200 { 201 int index = Collections.binarySearch(elements, o, getComparator()); 202 if (index >= 0) 203 { 204 remove(index); 205 } 206 return index; 207 } 208 209 212 public boolean remove(int index) 213 { 214 elements.remove(index); 215 fireIntervalRemoved(this, index, index); 216 217 return true; 218 } 219 220 223 public void clear() 224 { 225 int last = elements.size() - 1; 226 227 if (last >= 0) 228 { 229 elements.clear(); 230 fireIntervalRemoved(this, 0, last); 231 } 232 } 233 234 240 public String toString() 241 { 242 return elements.toString(); 243 } 244 } 245 | Popular Tags |