1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package nl.tudelft.goal.ut2004.visualizer.util;
18
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.LinkedList;
23
24 import cz.cuni.amis.utils.collections.ObservableCollection;
25
26
27
28
29
30
31
32
33 public class ObservingCollection<T> extends ObservableCollection<T> implements
34 Collection<T> {
35
36 private final Listener listener;
37 private ObservableCollection<T> observed;
38 private final ObservableCollection<T> empty = new ObservableCollection<T>(
39 new LinkedList<T>());;
40
41 public ObservingCollection() {
42 super(new LinkedList<T>());
43 this.listener = new Listener();
44 observed = new ObservableCollection<T>(new LinkedList<T>());
45 }
46
47 public void setObserved(ObservableCollection<T> newCol) {
48
49
50 synchronized (this) {
51
52 observed.removeCollectionListener(listener);
53 observed = newCol;
54 observed.addCollectionListener(listener);
55
56
57 privateClear();
58 privateAddAll(newCol);
59 }
60 }
61
62 public void removeObserved() {
63 setObserved(empty);
64 }
65
66 private void privateAddAll(Collection<T> c) {
67 super.addAll(c);
68 }
69
70 private void privateClear() {
71 super.clear();
72 }
73
74 private void privateRemoveAll(Collection<T> c) {
75 super.removeAll(c);
76 }
77
78
79
80
81 private class Listener extends CollectionEventAdaptor<T> {
82
83 @Override
84 public void postAddEvent(Collection<T> alreadyAdded,
85 Collection<T> whereWereAdded) {
86
87 synchronized (ObservingCollection.this) {
88
89 if (whereWereAdded == observed) {
90 privateAddAll(alreadyAdded);
91 }
92 }
93 }
94
95 @Override
96 public void postRemoveEvent(Collection<T> alreadyRemoved,
97 Collection<T> whereWereRemoved) {
98
99 synchronized (ObservingCollection.this) {
100
101 if (whereWereRemoved == observed) {
102 privateRemoveAll(alreadyRemoved);
103 }
104 }
105 }
106
107
108 }
109
110 @Override
111 public boolean add(T e) {
112 throw new UnsupportedOperationException("Unmodifyable");
113 }
114
115 @Override
116 public boolean addAll(Collection<? extends T> c) {
117 throw new UnsupportedOperationException("Unmodifyable");
118 }
119
120 @Override
121 public void clear() {
122 throw new UnsupportedOperationException("Unmodifyable");
123 }
124
125 @Override
126 public Iterator<T> iterator() {
127 return Collections.unmodifiableCollection(col).iterator();
128 }
129
130 @Override
131 public boolean remove(Object o) {
132 throw new UnsupportedOperationException("Unmodifyable");
133 }
134
135 @Override
136 public boolean removeAll(Collection<?> c) {
137 throw new UnsupportedOperationException("Unmodifyable");
138 }
139
140 @Override
141 public boolean retainAll(Collection<?> c) {
142 throw new UnsupportedOperationException("Unmodifyable");
143 }
144
145 }