File: Class.java /* */ import java.awt.*; import java.util.Date; public class Clock extends java.applet.Applet implements Runnable { // Instance variables Thread aThread; // Handle for Thread object Date date; // Handle for Date object Frame frame; // Handle for window (Frame object) Graphics graphics; // Handle for drawing graphics // A class variable to distinguish between Applet // and the standalone version private static boolean isApplet = true; // Constructor for Clock object, called whenever a // new object is created public Clock() { if (isApplet) { // Standalone version uses MakeWindow() Panel p = new Panel(); p.add(new Button("Start")); p.add(new Button("Stop")); add("North", p); } } // init() is called by the appletviewer when applet is // first loaded; gets the Applet's Panel's Graphics public void init() { graphics = getGraphics(); date = new Date(); } // paint() is called from run() and by appletviewer public void paint(Graphics g) { g.clearRect(25,25,150,50); g.drawString(date.toString(), 25, 60); } // start() is called when applet's panel becomes visible public void start() { if (aThread == null) { aThread = new Thread(this); aThread.start(); } } // stop() is called when the appletviewer changes pages public void stop() { if (aThread != null) { aThread.stop(); aThread = null; } } // run() gets called when Thread is started, stops // via stop() public void run() { while (true) { date = new Date(); paint(graphics); try {Thread.sleep(1000); } catch (InterruptedException e) {}; } } // action() is called when Stop button is clicked // within the Applet Panel public boolean action(Event e, Object arg) { if (e.target instanceof Button) { if (((String)arg).equals("Stop")) stop(); else start(); return true; } return false; } // main() is called only when started standalone public static void main(String args[]) { isApplet = false; Clock clock = new Clock(); clock.frame = new MakeWindow("Clock Window", clock); clock.graphics = clock.frame.getGraphics(); clock.start(); } } // A second helper class; could be in a separate file class MakeWindow extends Frame { // Instance variable Clock clock; // Constructor for new MakeWindow object public MakeWindow(String name, Clock applet) { super(name); clock = applet; Panel p = new Panel(); p.add(new Button("Start")); p.add(new Button("Stop")); add("North", p); resize(200, 110); show(); } public boolean handleEvent(Event e) { if (e.id == Event.ACTION_EVENT) { if (e.target instanceof Button) { String s = ((Button)e.target).getLabel(); if (s.equals("Stop")) clock.stop(); else clock.start(); } } else if (e.id == Event.WINDOW_DESTROY) { this.hide(); System.exit(0); } else super.handleEvent(e); return true; }