import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.applet.Applet;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class Test extends Applet implements WindowListener {

    public static void main(String args[]) {
        Frame F=new Frame("Applet/Application with a timer");
        F.setSize(480, 240); 

        Test A = new Test();
        F.add(A);
        A.init();
        A.start(); // Web browser calls start() automatically
        F.setVisible(true);
        F.addWindowListener(A);
    }


    private int    timer = 0;
    private Timer  count = null;
    private Label  label = null;

    public void init() {
        try {
            // this is applet specific, will always generate an exception in application
            setBackground(new Color(Integer.parseInt(getParameter("background"),16)));
        } catch (Exception e) {
            // default value for applet if no parameter, the only value for application
            setBackground(new Color(255,255,255));
        }

        setLayout(new BorderLayout());
        label = new Label(" starting clock ... ", Label.CENTER);
        add("North", label);        
    }

    public void start() {
        TimerTask Proc = new TimerTask() {
            public void run() {
                    timer++;
                    label.setText(""+new Date()+" displayed "+timer+" times");
            }
        };
        count = new Timer();
        count.schedule(Proc, 0, 100);
//      count.scheduleAtFixedRate(Proc, 0, 100);
    }

    public void stop() {
        // cancel stops further scheduling but will not wait
        // for the current run to finish, we should wait on our own
        count.cancel();
        try {
            Thread.currentThread().sleep(110);    
        } catch(Exception e) {} // we typically ignore this exception if it happens
     }


    // INTERFACE WindowListener
    public void windowClosing(WindowEvent e)      {
        stop();
        System.exit(0);
    }
    public void windowClosed(WindowEvent e)       {  }
    public void windowOpened(WindowEvent e)       {  }
    public void windowIconified(WindowEvent e)    {  }
    public void windowDeiconified(WindowEvent e)  {  }
    public void windowActivated(WindowEvent e)    {  }
    public void windowDeactivated(WindowEvent e)  {  }
    
}