The Basic Java Applet
First we will create simple applet. First lets make sure you understand what exactly an applet is. An applet is a small Java program that runs inside of a web browser. The applet is given a square location on the web browser, defined by a height and width. The applet can display to this location on the browser Window. Figure 1.1 shows a very simple applet.
Figure 1.1: A simple Hello World applet
Constructing an Applet
Now we will example the simple “Hello World” applet. The source code for the applet is shown in Listing 1.1.
Listing 1.1: A Basic Java Applet (BasicApplet.java)
import java.awt.*;
import java.applet.*;
public class BasicApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.BLACK);
g.drawString("Hello World",10,10);
}
}
You will notice that the applet extends from the Java class "Applet". This is what makes a Java class an applet.
You will also notice that the applet includes a method named "paint". The paint method is used to display the applet graphics to the web browser. The “paint” method is passed a "Graphics" object. This "Graphics" object is used to display to the browser.
In the rest of this article I will show you how to use this "Graphics" objects to display your applet’s text and graphics. I will begin by showing you how to display text and use multiple fonts.
Constructing an Applet's HTML
If you examine the source for this page you will notice that Figure 1.1 really is an applet. This is how the basic applet looks in the browser. If you are not seeing the Hello World applet in Figure 1.1, then you likely have Java disabled for your browser. Displaying an applet in Java is easy. You the code displayed here is all that was needed to display the above applet.
<APPLET CODE="BasicApplet.class" CODEBASE="/code/2/" WIDTH=200 HEIGHT=100></APPLET>
As you can see, the height and width of the applet are both specified. Applets must be specifically sized, and the applet cannot change its size once displayed. The Applet tag also specifies the location of the applet class file and its name.












