1 19 20 package swingwtx.swing; 21 22 import swingwt.awt.event.*; 23 24 import java.util.*; 25 26 public class Timer { 27 28 protected Vector actionListeners = new Vector(); 29 protected int delay = 100; 30 protected int initialDelay = 100; 31 protected boolean running = false; 32 protected boolean coalesce = true; 33 protected boolean repeats = true; 34 35 protected TimerThread timerThread = null; 36 37 public Timer(int delay, ActionListener l) { 38 this.delay = delay; 39 this.initialDelay = delay; 40 addActionListener(l); 41 } 42 43 public synchronized void addActionListener(ActionListener l) { 44 actionListeners.add(l); 45 } 46 47 public synchronized void removeActionListener(ActionListener l) { 48 actionListeners.remove(l); 49 } 50 51 protected synchronized void fireActionPerformed(ActionEvent e) { 52 Iterator i = actionListeners.iterator(); 53 while (i.hasNext()) { 54 ((ActionListener) i.next()).actionPerformed(e); 55 } 56 } 57 58 public synchronized int getDelay() { return delay; } 59 public synchronized int getInitialDelay() { return initialDelay; } 60 public synchronized boolean isCoalesce() { return coalesce; } 61 public synchronized boolean isRepeats() { return repeats; } 62 public synchronized boolean isRunning() { return running; } 63 public synchronized void restart() { delay = initialDelay; stop(); start(); } 64 public synchronized void setCoalesce(boolean b) { coalesce = b; } 65 public synchronized void setDelay(int delay) { this.delay = delay; } 66 public synchronized void setInitialDelay(int delay) { this.initialDelay = delay; } 67 public synchronized void setRepeats(boolean b) { repeats = b; } 68 protected synchronized void setRunning(boolean b) { running = b; } 69 70 public synchronized void start() { 71 if (!isRunning()) { 72 setRunning(true); 73 timerThread = new TimerThread(this); 74 timerThread.start(); 75 } 76 } 77 78 public synchronized void stop() { 79 setRunning(false); 80 timerThread = null; 81 } 82 83 } 84 85 class TimerThread extends Thread { 86 Timer timer = null; 87 public TimerThread(Timer t) { this.timer = t; } 88 public void run() { 89 while (timer.isRunning()) { 90 try { 91 Thread.sleep(timer.getDelay()); 92 } 93 catch (Exception e) { 94 } 95 SwingUtilities.invokeSync( new Runnable () { 97 public void run() { 98 timer.fireActionPerformed(new ActionEvent(timer, 0)); 99 } 100 }); 101 if (!timer.isRepeats()) break; 102 } 103 } 104 } 105 | Popular Tags |