/* Applet to display a countdown to an event in the future * (This is java 1.02 compatible code.) * * By Terry R. McConnell * * Call from HTML as follows: Things you might want to change in the code: - The font - The background color - The time between updates - The string to be printed when the date cannot be parsed - The string to be printed when time expires */ import java.awt.Graphics; import java.awt.Color; import java.awt.Font; import java.util.Date; import java.util.Date.*; public class CountDownApplet extends java.applet.Applet implements Runnable { private Font myFont = new Font("TimesRoman",Font.BOLD,12); private long targetTime; // Time we are counting down to. Times // are in milliseconds since 1970 private Date DateNow; private Thread myThread; private static final int pause = 1000; // time between steps // in milliseconds private static final String expiredString = "Expired"; private static final String invalidString = "Invalid Date"; private boolean initOk = true; // The init method is called when the applet starts public void init(){ setBackground(Color.red); String td = getParameter("targetDate"); if(td == null){ System.out.println("Unable to parse target date"); initOk = false; } else { targetTime = Date.parse(td); } } // The start method is called everytime the applet is (re)started // All this one does is begin a thread of execution. public void start(){ if(myThread == null){ myThread = new Thread(this); myThread.start(); } } public void stop(){ if(myThread != null){ myThread.stop(); myThread = null; // allow garbage collection } } // Called when a new thread is started public void run(){ while(true){ repaint(); try { Thread.sleep(pause);} catch (InterruptedException e) {} } } /* Update the countdown field. Since we create a new Date object every time this is called, the countdown is updated. Old date objects can be garbage collected. */ public void paint(Graphics g) { long secsOffset = 0L; if(initOk){ g.setFont(myFont); DateNow = new Date(); secsOffset = (targetTime - DateNow.getTime())/1000L; if(secsOffset >= 0L){ g.drawString("" + Long.toString(secsOffset),10,15); } else { g.drawString(expiredString,10,15); } } else { g.drawString(invalidString,10,15); } } }