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.

A simple applet

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"
        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 book, I show only the Java code, not the corresponding HTML file that goes with it. Typically, that ...

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.