01: /*
02: * Copyright 2007 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package com.google.gwt.user.client.ui;
17:
18: import java.util.Iterator;
19: import java.util.NoSuchElementException;
20:
21: /**
22: * A collection of convenience factories for creating iterators for widgets.
23: * This mostly helps developers support {@link HasWidgets} without having to
24: * implement their own {@link Iterator}.
25: */
26: class WidgetIterators {
27:
28: private static final Widget[] copyWidgetArray(final Widget[] widgets) {
29: final Widget[] clone = new Widget[widgets.length];
30: for (int i = 0; i < widgets.length; i++) {
31: clone[i] = widgets[i];
32: }
33: return clone;
34: }
35:
36: /**
37: * Wraps an array of widgets to be returned during iteration.
38: * <code>null</code> is allowed in the array and will be skipped during
39: * iteration.
40: *
41: * @param container the container of the widgets in <code>contained</code>
42: * @param contained the array of widgets
43: * @return the iterator
44: */
45: static final Iterator<Widget> createWidgetIterator(
46: final HasWidgets container, final Widget[] contained) {
47: return new Iterator<Widget>() {
48: int index = -1, last = -1;
49: boolean widgetsWasCopied = false;
50: Widget[] widgets = contained;
51:
52: {
53: gotoNextIndex();
54: }
55:
56: private void gotoNextIndex() {
57: ++index;
58: while (index < contained.length) {
59: if (contained[index] != null) {
60: return;
61: }
62: ++index;
63: }
64: }
65:
66: public boolean hasNext() {
67: return (index < contained.length);
68: }
69:
70: public Widget next() {
71: if (!hasNext()) {
72: throw new NoSuchElementException();
73: }
74: last = index;
75: final Widget w = contained[index];
76: gotoNextIndex();
77: return w;
78: }
79:
80: public void remove() {
81: if (last < 0) {
82: throw new IllegalStateException();
83: }
84:
85: if (!widgetsWasCopied) {
86: widgets = copyWidgetArray(widgets);
87: widgetsWasCopied = true;
88: }
89:
90: container.remove(contained[last]);
91: last = -1;
92: }
93: };
94: }
95:
96: private WidgetIterators() {
97: // Not instantiable.
98: }
99: }
|