1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.gui.util;
21
22 import java.awt.Component;
23 import java.awt.Container;
24 import java.util.Iterator;
25 import java.util.LinkedList;
26 import java.util.NoSuchElementException;
27 import javax.swing.JMenu;
28 import javax.swing.JPanel;
29 import javax.swing.JPopupMenu;
30 import javax.swing.JScrollPane;
31 import javax.swing.JViewport;
32
33 /***
34 * Provides an iterator that traverses a component's hierarchy in preorder.
35 *
36 * @author Steffen Pingel
37 */
38 public class ComponentIterator implements Iterator<Component> {
39
40 private LinkedList<Component> stack = new LinkedList<Component>();
41 private Component lookAhead = null;
42
43 /***
44 * Iterate over hierarchy of <code>component</code>. First call to next
45 * will return <code>component</code>.
46 */
47 public ComponentIterator(Component component)
48 {
49 stack.add(component);
50 }
51
52 /***
53 * Not supported.
54 *
55 * @throws UnsupportedOperationException
56 */
57 public void remove()
58 {
59 throw new UnsupportedOperationException();
60 }
61
62 public boolean hasNext()
63 {
64 if (lookAhead == null) {
65 lookAhead = findNext();
66 }
67 return lookAhead != null;
68 }
69
70 public Component next()
71 {
72 if (lookAhead == null) {
73 lookAhead = findNext();
74 if (lookAhead == null) {
75 throw new NoSuchElementException();
76 }
77 }
78 Component result = lookAhead;
79 lookAhead = null;
80 return result;
81 }
82
83 private Component findNext()
84 {
85 while (!stack.isEmpty()) {
86 Component c = (Component)stack.removeLast();
87 if (c instanceof JMenu) {
88 c = ((JMenu)c).getPopupMenu();
89 }
90 else if (c instanceof JScrollPane) {
91 c = ((JScrollPane)c).getViewport();
92 }
93 if (c instanceof JPanel
94 || c instanceof JPopupMenu
95 || c instanceof JViewport) {
96
97 for (int i = ((Container)c).getComponentCount() - 1; i >= 0; i--) {
98 Component component = ((Container)c).getComponent(i);
99 stack.addLast(component);
100 }
101 }
102 else {
103 return c;
104 }
105 }
106 return null;
107 }
108
109 }