[ Team LiB ] Previous Section Next Section

16.2 A First Applet

Example 16-1 shows what is probably the simplest possible applet you can write in Java. Figure 16-1 shows the output it produces. This example introduces the paint( ) method, which is invoked by the applet viewer (or web browser) when the applet needs to be drawn. This method should perform graphical output—such as drawing text or lines or displaying images—for your applet. The argument to paint( ) is a java.awt.Graphics object that you use to do the drawing.

Figure 16-1. A simple applet
Example 16-1. FirstApplet.java
package je3.applet;
import java.applet.*;   // Don't forget this import statement!
import java.awt.*;      // Or this one for the graphics!

/** This applet just says "Hello World" */
public class FirstApplet extends Applet {
    // 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="je3.applet.FirstApplet.class"
        width=150 height=100>

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 book, 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.

    [ Team LiB ] Previous Section Next Section