1 | package org.apollo.mvc;
|
---|
2 |
|
---|
3 | import java.util.LinkedList;
|
---|
4 | import java.util.Queue;
|
---|
5 |
|
---|
6 | import org.expeditee.gio.EcosystemManager;
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * If your observer needs to reacts to events on the swing thread (i.e. interacting with swing
|
---|
10 | * objects somewhere in the event) and the observed subject raised events on other threads,
|
---|
11 | * this class tunnels all events into the swing thread and ensures that they are raised in
|
---|
12 | * the swing thread (thread safety!).
|
---|
13 | *
|
---|
14 | * @author Brook Novak
|
---|
15 | *
|
---|
16 | */
|
---|
17 | public class SwingEventQueue {
|
---|
18 |
|
---|
19 | private SwingThreadedObserver target;
|
---|
20 |
|
---|
21 | // Using a FIFO queue implementation
|
---|
22 | private Queue<QueudEvent> eventQueue = new LinkedList<QueudEvent>();
|
---|
23 |
|
---|
24 | private EventProccessor eventProccessor = new EventProccessor();
|
---|
25 |
|
---|
26 | /**
|
---|
27 | * COnstructor.
|
---|
28 | * @param target The SwingThreadedObserver instance to tunnel events to on the swing thread.
|
---|
29 | */
|
---|
30 | public SwingEventQueue(SwingThreadedObserver target) {
|
---|
31 | if (target == null) throw new NullPointerException("target");
|
---|
32 | this.target = target;
|
---|
33 | }
|
---|
34 |
|
---|
35 | /**
|
---|
36 | * Adds an event to the wing queue. The event will be re-fired on the swing thread
|
---|
37 | * and raised on the target.
|
---|
38 | *
|
---|
39 | * @param event A type of SubjectChangedEvent
|
---|
40 | * @param source The subject which the event was fired from
|
---|
41 | */
|
---|
42 | public synchronized void queueEvent(Subject source, SubjectChangedEvent event) {
|
---|
43 | synchronized (eventQueue) {
|
---|
44 | eventQueue.add(new QueudEvent(source, event));
|
---|
45 | }
|
---|
46 | EcosystemManager.getMiscManager().runOnGIOThread(eventProccessor);
|
---|
47 | }
|
---|
48 |
|
---|
49 | class EventProccessor implements Runnable {
|
---|
50 |
|
---|
51 | public void run() { // invoked on swing thread
|
---|
52 |
|
---|
53 | synchronized (eventQueue) {
|
---|
54 | while (!eventQueue.isEmpty()) {
|
---|
55 | QueudEvent qe = eventQueue.remove();
|
---|
56 | target.modelChangedOnSwingThread(qe.source, qe.event);
|
---|
57 | }
|
---|
58 | }
|
---|
59 | }
|
---|
60 |
|
---|
61 | }
|
---|
62 |
|
---|
63 | class QueudEvent {
|
---|
64 | public QueudEvent(Subject source, SubjectChangedEvent event) {
|
---|
65 | this.event = event;
|
---|
66 | this.source = source;
|
---|
67 | }
|
---|
68 | SubjectChangedEvent event;
|
---|
69 | Subject source;
|
---|
70 | }
|
---|
71 |
|
---|
72 | }
|
---|