Java Reference
In-Depth Information
Example 15−1: FirstApplet.java (continued)
// This method displays the applet.
public void paint(Graphics g) {
g.drawString("Hello World", 25, 50);
}
}
To display an applet, you need an HTML file that references it. Here is an HTML
fragment that can be used with this first applet:
<applet code="com.davidflanagan.examples.applet.FirstApplet.class"
codebase="../../../../"
width=150 height=100>
</applet>
With an HTML file that references the applet, you can now view the applet with
an applet viewer or web browser. Note that the WIDTH and HEIGHT attributes of this
HTML tag are required. For most applet examples in this topic, I show only the
Java code, not the corresponding HTML file that goes with it. Typically, that HTML
file contains a tag as simple as the one shown here.
A Clock Applet
Example 15-2 is an applet that displays the current time, as shown in Figure 15-2,
and updates it once a second. Unlike Example 15-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.
Figur e 15−2. A clock applet
In order to update the time every second, Clock implements the Runnable inter-
face 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. Some applet viewers provide an interface for displaying this
information.
Search WWH ::




Custom Search