| 1 | |
package biz.xsoftware.examples.timer; |
| 2 | |
|
| 3 | |
import java.util.HashMap; |
| 4 | |
import java.util.Map; |
| 5 | |
import java.util.TimerTask; |
| 6 | |
|
| 7 | |
import javax.swing.event.EventListenerList; |
| 8 | |
|
| 9 | |
import biz.xsoftware.examples.advanced.ScheduleListener; |
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
public class CalendarServiceImpl implements CalendarService { |
| 16 | |
|
| 17 | |
private TimerInterface timer; |
| 18 | 2 | private EventListenerList listenerList = new EventListenerList(); |
| 19 | 2 | private Map<String, CalendarEvent> titleToEvent = new HashMap<String, CalendarEvent>(); |
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | 2 | public CalendarServiceImpl(TimerInterface t) { |
| 26 | 2 | timer = t; |
| 27 | 2 | } |
| 28 | |
|
| 29 | |
|
| 30 | |
|
| 31 | |
public void addEvent(String title, long delay) { |
| 32 | 2 | CalendarEvent evt = new CalendarEvent(title); |
| 33 | 2 | titleToEvent.put(title, evt); |
| 34 | 2 | timer.schedule(evt, delay); |
| 35 | 2 | } |
| 36 | |
|
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | |
public void addScheduleListener(ScheduleListener l) { |
| 41 | 2 | listenerList.add(ScheduleListener.class, l); |
| 42 | 2 | } |
| 43 | |
|
| 44 | |
|
| 45 | |
|
| 46 | |
public void removeScheduleListener(ScheduleListener l) { |
| 47 | 2 | listenerList.remove(ScheduleListener.class, l); |
| 48 | 2 | } |
| 49 | |
private class CalendarEvent extends TimerTask { |
| 50 | |
|
| 51 | |
private String title; |
| 52 | |
|
| 53 | |
|
| 54 | |
|
| 55 | 2 | public CalendarEvent(String title) { |
| 56 | 2 | this.title = title; |
| 57 | 2 | } |
| 58 | |
|
| 59 | |
|
| 60 | |
|
| 61 | |
@Override |
| 62 | |
public void run() { |
| 63 | 1 | fireEventStarted(title); |
| 64 | 1 | } |
| 65 | |
} |
| 66 | |
|
| 67 | |
|
| 68 | |
|
| 69 | |
protected void fireEventStarted(String title) { |
| 70 | |
|
| 71 | 1 | Object[] listeners = listenerList.getListenerList(); |
| 72 | |
|
| 73 | |
|
| 74 | 2 | for (int i = listeners.length-2; i>=0; i-=2) { |
| 75 | 1 | if (listeners[i]==ScheduleListener.class) { |
| 76 | 1 | ((ScheduleListener)listeners[i+1]).eventStarted(title); |
| 77 | |
} |
| 78 | |
} |
| 79 | 1 | } |
| 80 | |
|
| 81 | |
|
| 82 | |
|
| 83 | |
public void cancelEvent(String title) { |
| 84 | 1 | CalendarEvent event = titleToEvent.get(title); |
| 85 | 1 | timer.cancelTask(event); |
| 86 | 1 | } |
| 87 | |
} |