298 Part I: The Java Language
After you enter the source code forSimpleApplet, compile in the same way that you
have been compiling programs. However, runningSimpleAppletinvolves a different process.
In fact, there are two ways in which you can run an applet:
- Executing the applet within a Java-compatible web browser.
- Using an applet viewer, such as the standard tool,appletviewer. An applet viewer
executes your applet in a window. This is generally the fastest and easiest way to
test your applet.
Each of these methods is described next.
To execute an applet in a web browser, you need to write a short HTML text file that
contains a tag that loads the applet. Currently, Sun recommends using the APPLET tag for
this purpose. Here is the HTML file that executesSimpleApplet:
<applet code="SimpleApplet" width=200 height=60>
</applet>
Thewidthandheightstatements specify the dimensions of the display area used by the
applet. (The APPLET tag contains several other options that are examined more closely in
Part II.) After you create this file, you can execute your browser and then load this file, which
causesSimpleAppletto be executed.
To executeSimpleAppletwith an applet viewer, you may also execute the HTML file
shown earlier. For example, if the preceding HTML file is calledRunApp.html, then the
following command line will runSimpleApplet:
C:\>appletviewer RunApp.html
However, a more convenient method exists that you can use to speed up testing. Simply
include a comment at the head of your Java source code file that contains the APPLET tag.
By doing so, your code is documented with a prototype of the necessary HTML statements,
and you can test your compiled applet merely by starting the applet viewer with your Java
source code file. If you use this method, theSimpleAppletsource file looks like this:
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
With this approach, you can quickly iterate through applet development by using these
three steps:
- Edit a Java source file.
- Compile your program.