A Clock Applet
Example 16-2
is an applet that displays the current time, as shown in Figure 16-2, and updates it once
every second. Unlike Example
16-1, which defines a paint(
)
method and does its own text drawing with Graphics.drawString( )
, this example uses a
java.awt.Label
component to do the
drawing. While it is common for applets to do their own drawing with a
paint( )
method, it is also
important to remember that applets extend java.awt.Panel
and can contain any type of
GUI components. Clock
defines an
init( )
method that creates and
configures the Label
component.
Figure 16-2. A clock applet
In order to update the time every second, Clock
implements the Runnable
interface and creates a Thread
that runs the run( )
method. The applet’s start( )
and stop(
)
methods are invoked by the browser when the applet becomes
visible or is hidden; they start and stop the thread. (Although the
example is written to use Java 1.1, it does not rely on the Thread.stop( )
method, which was deprecated
in Java 1.2.)
Finally, the Clock
applet implements getAppletInfo( )
to provide information about the applet. Sun’s
appletviewer tool is able to display this
information, but most web browsers don’t.
Example 16-2. Clock.java
package je3.applet; import java.applet.*; // Don't forget this import statement! import java.awt.*; // Or this one for the graphics! import java.util.Date; // To obtain ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.