/*
 * Cay S. Horstmann & Gary Cornell, Core Java
 * Published By Sun Microsystems Press/Prentice-Hall
 * Copyright (C) 1997 Sun Microsystems Inc.
 * All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this 
 * software and its documentation for NON-COMMERCIAL purposes
 * and without fee is hereby granted provided that this 
 * copyright notice appears in all copies. 
 * 
 * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR 
 * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
 * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED 
 * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING 
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */
 
/**
 * @version 1.10 23 Jun 1997
 * @author Cay Horstmann
 */

import java.awt.*;
import java.util.*;
import java.io.*;

public class TimerBean implements Runnable, Serializable
{  public int getInterval() { return interval; }
   public void setInterval(int i) { interval = i; }

   public boolean isRunning() { return runner != null; }
   public void setRunning(boolean b)
   {  if (b && runner == null)
      {  runner = new Thread(this);
         runner.start();
      }
      else if (!b && runner != null)
      {  runner.stop();
         runner = null;
      }
   }
 
   public synchronized void addTimerListener
      (TimerListener l) 
   {  timerListeners.addElement(l);
   }
   
   public synchronized void removeTimerListener
      (TimerListener l) 
   {  timerListeners.removeElement(l);
   }

   public void fireTimerEvent(TimerEvent evt)
   {  Vector currentListeners = null;
      synchronized(this) 
      {  currentListeners = (Vector)timerListeners.clone();
      }
      for (int i = 0; i < currentListeners.size(); i++) 
      {  TimerListener listener 
            = (TimerListener)currentListeners.elementAt(i);
         listener.timeElapsed(evt);
      }
   }


   public void run()
   {  if (interval <= 0) return;
      while (true)
      {  try { Thread.sleep(interval); } 
         catch(InterruptedException e) {}
         fireTimerEvent(new TimerEvent(this));
      }
   }

   private int interval = 1000;
   private Vector timerListeners = new Vector();
   private Thread runner;
}



