1 19 package jcckit.data; 20 21 import java.text.*; 22 import java.util.*; 23 24 44 public abstract class DataContainer { 45 private final static String TEMPLATE 46 = "Invalid operation: {0}, Element: {1}, Container: {2}"; 47 final static String ADD = "add", 48 REPLACE = "replace", 49 INSERT = "insert"; 50 51 private final Vector _listeners = new Vector(); 52 private final Vector _container = new Vector(); 53 54 55 public void addDataListener(DataListener listener) { 56 if (!_listeners.contains(listener)) { 57 _listeners.addElement(listener); 58 } 59 } 60 61 62 public void removeDataListener(DataListener listener) { 63 _listeners.removeElement(listener); 64 } 65 66 private void notifyListeners(DataEvent event) { 67 for (int i = 0, n = _listeners.size(); i < n; i++) { 68 ((DataListener) _listeners.elementAt(i)).dataChanged(event); 69 } 70 if (this instanceof DataElement) { 72 DataContainer container = ((DataElement) this).getContainer(); 73 if (container != null) { 74 container.notifyListeners(event); 75 } 76 } 77 } 78 79 80 public int getNumberOfElements() { 81 return _container.size(); 82 } 83 84 85 public DataElement getElement(int index) { 86 return (DataElement) _container.elementAt(index); 87 } 88 89 94 public int getIndexOf(DataElement element) { 95 return _container.indexOf(element); 96 } 97 98 105 public void addElement(DataElement element) { 106 if (isValid(element)) { 107 _container.addElement(element); 108 element.setContainer(this); 109 notifyListeners(DataEvent.createAddEvent(this)); 110 } else { 111 throwException(ADD, element); 112 } 113 } 114 115 125 public void insertElementAt(int index, DataElement element) { 126 if (isValid(element)) { 127 _container.insertElementAt(element, index); 128 element.setContainer(this); 129 notifyListeners(DataEvent.createInsertEvent(this, index)); 130 } else { 131 throwException(INSERT, element); 132 } 133 } 134 135 142 public void removeElementAt(int index) { 143 DataElement element = (DataElement) _container.elementAt(index); 144 element.setContainer(null); 145 _container.removeElementAt(index); 146 notifyListeners(DataEvent.createRemoveEvent(this, index, element)); 147 } 148 149 159 public void replaceElementAt(int index, DataElement element) { 160 if (isValid(element)) { 161 DataElement oldElement = (DataElement) _container.elementAt(index); 162 oldElement.setContainer(null); 163 _container.setElementAt(element, index); 164 element.setContainer(this); 165 notifyListeners(DataEvent.createReplaceEvent(this, index, oldElement)); 166 } else { 167 throwException(REPLACE, element); 168 } 169 } 170 171 private void throwException(String operation, DataElement element) { 172 throw new IllegalArgumentException (MessageFormat.format(TEMPLATE, 173 new Object [] {operation, element, this.getClass().getName()})); 174 } 175 176 181 protected abstract boolean isValid(DataElement element); 182 } 183 | Popular Tags |