FileDocCategorySizeDatePackage
Clock.javaAPI DocExample3484Sat Jan 24 10:44:38 GMT 2004je3.applet

Clock

public class Clock extends Applet implements Runnable
This applet displays the time, and updates it every second

Fields Summary
Label
time
DateFormat
timeFormat
Thread
timer
volatile boolean
running
Constructors Summary
Methods Summary
public java.lang.StringgetAppletInfo()
Returns information about the applet for display by the applet viewer

	return "Clock applet Copyright (c) 2000 by David Flanagan";
    
public voidinit()
The init method is called when the browser first starts the applet. It sets up the Label component and obtains a DateFormat object

	time = new Label();
	time.setFont(new Font("helvetica", Font.BOLD, 12));
	time.setAlignment(Label.CENTER);
	setLayout(new BorderLayout());
	add(time, BorderLayout.CENTER);
	timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
    
public voidrun()
This method implements Runnable. It is the body of the thread. Once a second, it updates the text of the Label to display the current time. AWT and Swing components are not, in general, thread-safe, and should typically only be updated from the event-handling thread. We can get away with using a separate thread here because there is no event handling in this applet, and this component will never be modified by any other thread.

	while(running) {     // Loop until we're stopped
	    // Get current time, convert to a String, and display in the Label
	    time.setText(timeFormat.format(new Date()));  
	    // Now wait 1000 milliseconds
	    try { Thread.sleep(1000); }
	    catch (InterruptedException e) {}
	}
	// If the thread exits, set it to null so we can create a new one
	// if start() is called again.
	timer = null;
    
public voidstart()
This browser calls this method to tell the applet to start running. Here, we create and start a thread that will update the time each second. Note that we take care never to have more than one thread

	running = true;                // Set the flag 
	if (timer == null) {           // If we don't already have a thread
	    timer = new Thread(this);  // Then create one
	    timer.start();             // And start it running
	}
    
public voidstop()
The browser calls this method to tell the applet that it is not visible and should not run. It sets a flag that tells the run() method to exit

 running = false;