/* * ========================================================================= * Clock.java : A subclass of Applet which implements the Runnable interface. * The thread in this class updates and redraws the time every second. * * Adapted from : Campione M., Walrath K., Huml A., The Java Tutorial, 2000 * Modified by : Vasilios Lagakos March, 2001 * ========================================================================== */ import java.awt.Graphics; import java.awt.Color; import java.util.Date; public class Clock extends java.applet.Applet implements Runnable { private Thread clockThread = null; public void init() { setBackground(Color.white); } public void start() { if (clockThread == null) { clockThread = new Thread(this, "Clock"); clockThread.start(); } } /* Execution of the thread. Updates time every second once thread wakes up */ public void run() { Thread myThread = Thread.currentThread(); while (clockThread == myThread) { repaint(); try { Thread.sleep(1000); } catch (InterruptedException e){ } } } /* Gets the current time and draws it to the screen */ public void paint(Graphics g) { Date now = new Date(); g.drawString(now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(), 5, 10); } /* Overrides Applet's stop method and not Thread's stop method. */ public void stop() { /* It is better to stay away from the Thread's stop method. A better way to stop a thread is to have the thread's run method check a flag every time around its loop. Just change the flag like what is done in this method to stop the thread. This gives you much better control over where in the code the thread gets stopped, and lets you perform cleanup operations. */ clockThread = null; } }