Previous


1.1 Changes: Clock Applet

The paint method in the Clock applet uses the Date class to get the current time and format it. This API is not amenable to internationalization and has been deprecated in favour of methods in the new Calendar and DateFormat classes.

Here's the JDK 1.1 version of the Clock applet using the new API:


import java.awt.Graphics;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;

public class Clock1_1 extends java.applet.Applet implements Runnable {

    Thread clockThread = null;

    public void start() {
        if (clockThread == null) {
            clockThread = new Thread(this, "Clock");
            clockThread.start();
        }
    }
    public void run() {
        // loop terminates when clockThread is set to null in stop()
        while (Thread.currentThread() == clockThread) {
            repaint();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e){
            }
        }
    }
    public void paint(Graphics g) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        DateFormat dateFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT,
                                                 Locale.US);
        g.drawString(dateFormatter.format(date), 5, 10);
    }
    public void stop() {
        clockThread = null;
    }
}
And here's the new Clock applet running:

Since you can't run the applet, here's a picture of it:

See Writing Global Programs(in the new JDK 1.1 documentation) for a discussion about managing dates and times in a global fashion.


Previous