1 package nl.tudelft.simulation.dsol.swing.introspection.gui;
2
3 import java.awt.Component;
4 import java.lang.ref.WeakReference;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.List;
8 import java.util.Timer;
9 import java.util.TimerTask;
10
11
12
13
14
15
16
17
18
19
20 public class UpdateTimer extends TimerTask
21 {
22
23 @SuppressWarnings("unchecked")
24 private WeakReference<Component>[] components = new WeakReference[0];
25
26
27 private Timer timer = null;
28
29
30 private long period = 300L;
31
32
33
34
35
36 public UpdateTimer(final long period)
37 {
38 super();
39 this.period = period;
40 }
41
42
43
44
45
46 @SuppressWarnings("unchecked")
47 public synchronized void add(final Component component)
48 {
49 List<WeakReference<Component>> arrayList = new ArrayList<WeakReference<Component>>(Arrays.asList(this.components));
50 arrayList.add(new WeakReference<Component>(component));
51 this.components = arrayList.toArray(new WeakReference[arrayList.size()]);
52
53 if (this.timer == null)
54 {
55 this.timer = new Timer(true);
56 this.timer.scheduleAtFixedRate(this, 0L, this.period);
57 }
58 }
59
60
61
62
63
64 public synchronized void remove(final Component component)
65 {
66 for (int i = (this.components.length - 1); i > -1; i--)
67 {
68 if (this.components[i].get().equals(component))
69 {
70 this.remove(this.components[i]);
71 }
72 }
73 }
74
75
76
77
78
79 @SuppressWarnings("unchecked")
80 private synchronized void remove(final WeakReference<Component> reference)
81 {
82 List<WeakReference<Component>> arrayList = new ArrayList<WeakReference<Component>>(Arrays.asList(this.components));
83 arrayList.remove(reference);
84 this.components = arrayList.toArray(new WeakReference[arrayList.size()]);
85 if (this.components.length == 0)
86 {
87
88 this.timer.cancel();
89 }
90 }
91
92
93 @Override
94 public void run()
95 {
96 for (int i = (this.components.length - 1); i > -1; i--)
97 {
98 Component component = this.components[i].get();
99 if (component != null)
100 {
101 component.repaint();
102 }
103 else
104 {
105 this.remove(this.components[i]);
106 }
107 }
108 }
109 }