1 16 package com.google.gwt.user.client.ui; 17 18 import java.util.Iterator ; 19 import java.util.NoSuchElementException ; 20 21 34 public class WidgetCollection { 35 36 private class WidgetIterator implements Iterator { 37 38 private int index = -1; 39 40 public boolean hasNext() { 41 return index < (size - 1); 42 } 43 44 public Object next() { 45 if (index >= size) { 46 throw new NoSuchElementException (); 47 } 48 return array[++index]; 49 } 50 51 public void remove() { 52 if ((index < 0) || (index >= size)) { 53 throw new IllegalStateException (); 54 } 55 parent.remove(array[index--]); 56 } 57 } 58 59 private static final int INITIAL_SIZE = 4; 60 61 private Widget[] array; 62 private HasWidgets parent; 63 private int size; 64 65 71 public WidgetCollection(HasWidgets parent) { 72 this.parent = parent; 73 array = new Widget[INITIAL_SIZE]; 74 } 75 76 81 public void add(Widget w) { 82 insert(w, size); 83 } 84 85 91 public boolean contains(Widget w) { 92 return (indexOf(w) != -1); 93 } 94 95 102 public Widget get(int index) { 103 if ((index < 0) || (index >= size)) { 104 throw new IndexOutOfBoundsException (); 105 } 106 107 return array[index]; 108 } 109 110 117 public int indexOf(Widget w) { 118 for (int i = 0; i < size; ++i) { 119 if (array[i] == w) { 120 return i; 121 } 122 } 123 124 return -1; 125 } 126 127 135 public void insert(Widget w, int beforeIndex) { 136 if ((beforeIndex < 0) || (beforeIndex > size)) { 137 throw new IndexOutOfBoundsException (); 138 } 139 140 if (size == array.length) { 142 Widget[] newArray = new Widget[array.length * 2]; 143 for (int i = 0; i < array.length; ++i) { 144 newArray[i] = array[i]; 145 } 146 array = newArray; 147 } 148 149 ++size; 150 151 for (int i = size - 1; i > beforeIndex; --i) { 153 array[i] = array[i - 1]; 154 } 155 156 array[beforeIndex] = w; 157 } 158 159 165 public Iterator iterator() { 166 return new WidgetIterator(); 167 } 168 169 175 public void remove(int index) { 176 if ((index < 0) || (index >= size)) { 177 throw new IndexOutOfBoundsException (); 178 } 179 180 --size; 181 for (int i = index; i < size; ++i) { 182 array[i] = array[i + 1]; 183 } 184 185 array[size] = null; 186 } 187 188 194 public void remove(Widget w) { 195 int index = indexOf(w); 196 if (index == -1) { 197 throw new NoSuchElementException (); 198 } 199 200 remove(index); 201 } 202 203 208 public int size() { 209 return size; 210 } 211 } 212 | Popular Tags |