/********************************************* * Applet that demonstrates some basic animation * techniques. ********************************************/ import java.awt.*; import java.util.Calendar; public class DigitalClock extends java.applet.Applet implements Runnable { // the thread that will handle the redrawing ie the "ticking" protected Thread clockThread = null; // the font for the clock protected Font font = new Font("Monospaced", Font.BOLD, 48); // the color for the clock protected Color color = Color.green; // until we discuss Java threading, please use this // as a guide on how to start your animation thread public void start() { if (clockThread == null) { clockThread = new Thread(this); clockThread.start(); } } // stops the clock from "ticking" or redrawing public void stop() { clockThread = null; } // this is what you tell the thread to do // all it does is call the repaint method // and then go to sleep for 1000 miliseconds (1 second) // again use this as an example on how to do animation public void run() { while (Thread.currentThread() == clockThread) { repaint(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) {} } } // where most of the work is done. // responsible for repainting the applet area public void paint(Graphics g) { // the calendar is used to get the current time Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); g.setFont(font); g.setColor(color); // the draw string method takes the string to draw and the // x and y coordinates of where to put it. // remember that x,y is the lower left corner of the string. // the division and modulo operators are to get the time to // be in the form hh:mm:ss. If we didn't do the division // we wouldn't have the 2 digit minutes and seconds. g.drawString(hour + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10, 10, 60); } }