Day 8

Java Applet Basics

by Laura Lemay


Much of Java's current popularity has come about because of Java-enabled World Wide Web browsers and their support for applets-Java programs that run on Web pages and can be used to create dynamic, interactive Web sites. Applets, as noted at the beginning of this book, are written in the Java language, and can be viewed in any browser that supports Java, including Netscape's Navigator and Microsoft's Internet Explorer. Learning how to create applets is most likely the reason you bought this book, so let's waste no more time.

Last week, you focused on learning about the Java language itself, and most of the little programs you created were Java applications. This week, now that you have the basics down, you'll move on to creating and using applets, which includes a discussion of many of the classes in the standard Java class library.

Today you'll start with the basics:

How Applets and Applications Are Different

Although you explored the differences between Java applications and Java applets in the early part of this book, let's review them.

In short, Java applications are standalone Java programs that can be run by using just the Java interpreter, for example, from a command line. Most everything you've used up to this point in the book has been a Java application, albeit a simple one.

Java applets, however, are run from inside a World Wide Web browser. A reference to an applet is embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on the local system (the one the browser is running on). (The Java interpreter is built into the browser and runs the compiled Java class file from there.)

Because Java applets run inside a Java browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context, and the surrounding user interface. Java applications can also create this structure (allowing you to create graphical applications), but they don't require it (you'll learn how to create Java applications that use applet-like graphics and user interface (UI) features on Day 14, "Windows, Networking, and Other Tidbits").

Note that a single Java program can be written to operate as both a Java application and a Java applet. While you use different procedures and rules to create applets and applications, none of those procedures or rules conflict with each other. The features specific to applets are ignored when the program runs as an application, and vice versa. Keep this in mind as you design your own applets and applications.

One final significant difference between Java applets and applications-probably the biggest difference-is the set of restrictions placed on how applets can operate in the name of security. Given the fact that Java applets can be downloaded from any site on the World Wide Web and run on a client's system, Java-enabled browsers and tools limit what can be done to prevent a rogue applet from causing system damage or security breaches. Without these restrictions in place, Java applets could be written to contain viruses or trojan horses (programs that seem friendly but do some sort of damage to the system), or be used to compromise the security of the system that runs them. The restrictions on applets include the following:

All these rules are true for Java applets running Netscape Navigator or Microsoft Internet Explorer. Other Java-enabled browsers or tools may allow you to configure the level of security you want-for example, the appletviewer tool in the JDK allows you to set an access control list for which directories an applet can read or write. However, as an applet developer, it's safe to assume that most of your audience is going to be viewing your applets in a browser that implements the strictest rules for what an applet can do. Java applications have none of these restrictions.

The security restrictions imposed on applets are sometimes called "the sandbox" (as in applets are only allowed to play in the sandbox and can go no further). Work is being done by Sun and by the Java community to find ways for applets to be able to break out of the sandbox, including digital signatures and encryption. On Day 21, "Under the Hood," you'll learn more details on Java and applet security.

In addition to the applet restrictions listed, Java itself includes various forms of security and consistency checking in the Java compiler and interpreter for all Java programs to prevent unorthodox use of the language (you'll learn more about this on Day 21). This combination of restrictions and security features makes it more difficult for a rogue Java applet to do damage to the client's system.

These restrictions prevent all of the traditional ways of causing damage to a client's system, but it's impossible to be absolutely sure that a clever programmer cannot somehow work around these restrictions, violate privacy, use CPU resources, or just plain be annoying. Sun has asked the Net at large to try to break Java's security and to create an applet that can work around the restrictions imposed on it, and, in fact, several problems have been unearthed and fixed, usually relating to loading classes and to connecting to unauthorized sites. You'll learn about more issues in Java security on Day 21.

Creating Applets

For the most part, all the Java programs you've created up to this point have been Java applications-simple programs with a single main() method that create objects, set instance variables, and run methods. Today and in the next few days you'll be creating applets exclusively, so you will need a good grasp of how an applet works, the sorts of features an applet has, and where to start when you first create your own applets.

To create an applet, you create a subclass of the class Applet. The Applet class, part of the java.applet package, provides much of the behavior your applet needs to work inside a Java-enabled browser. Applets also take strong advantage of Java's Abstract Windowing Toolkit (awt), which provides behavior for creating graphical user interface (GUI)-based applets and applications: drawing to the screen; creating windows, menu bars, buttons, check boxes, and other UI elements; and managing user input such as mouse clicks and keypresses. The awt classes are part of the java.awt package.

New Term
Java's Abstract Windowing Toolkit (awt) provides classes and behavior for creating GUI-based applications in Java. Applets make use of many of the capabilities in the awt.

Although your applet can have as many additional "helper" classes as it needs, it's the main applet class that triggers the execution of the applet. That initial applet class always has a signature like this:

public class myClass extends java.applet.Applet {

Note the public keyword. Java requires that your applet subclass be declared public. Again, this is true only of your main applet class; any helper classes you create do not necessarily need to be public. public, private, and other forms of access control are described on Day 15, "Modifiers, Access Control, and Class Design."

When a Java-enabled browser encounters your applet in a Web page, it loads your initial applet class over the network, as well as any other helper classes that first class uses, and runs the applet using the browser's built-in bytecode interpreter. Unlike with applications, where Java calls the main() method directly on your initial class, when your applet is loaded, Java creates an instance of the applet class, and a series of special applet methods are called on that instance. Different applets that use the same class use different instances, so each one can behave differently from the other applets running in the same browser.

Major Applet Activities

To create a basic Java application, your class has to have one method, main(), with a specific signature. Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run. Applets are similar but more complicated-and, in fact, applets don't need a main() method at all. Applets have many different activities that correspond to various major events in the life cycle of the applet-for example, initialization, painting, and mouse events. Each activity has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods.

The default implementations of these activity methods do nothing; to provide behavior for an event you must override the appropriate method in your applet's subclass. You don't have to override all of them, of course; different applet behavior requires different methods to be overridden.

You'll learn about the various important methods to override as the week progresses, but, for a general overview, here are five of the most important methods in an applet's execution: initialization, starting, stopping, destroying, and painting.


Initialization occurs when the applet is first loaded (or reloaded), similarly to the main() method in applications. The initialization of an applet might include reading and parsing any parameters to the applet, creating any helper objects it needs, setting up an initial state, or loading images or fonts. To provide behavior for the initialization of your applet, override the init() method in your applet class:

public void init() {


After an applet is initialized, it is started. Starting is different from initialization because it can happen many different times during an applet's lifetime, whereas initialization happens only once. Starting can also occur if the applet was previously stopped. For example, an applet is stopped if the reader follows a link to a different page, and it is started again when the reader returns to this page. To provide startup behavior for your applet, override the start() method:

public void start() {

Functionality that you put in the start() method might include creating and starting up a thread to control the applet, sending the appropriate messages to helper objects, or in some way telling the applet to begin running. You'll learn more about starting applets on Day 10, "Simple Animation and Threads."


Stopping and starting go hand in hand. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). By default, when the reader leaves a page, any threads the applet had started will continue running. You'll learn more about threads on Day 10. By overriding stop(), you can suspend execution of these threads and then restart them if the applet is viewed again:

public void stop() {


Destroying sounds more violent than it is. Destroying enables the applet to clean up after itself just before it is freed or the browser exits-for example, to stop and remove any running threads, close any open network connections, or release any other running objects. Generally, you won't want to override destroy() unless you have specific resources that need to be released-for example, threads that the applet has created. To provide clean-up behavior for your applet, override the destroy() method:

public void destroy() {

Technical Note
How is destroy() different from finalize(), which was described on Day 7, "More About Methods"? First, destroy() applies only to applets. finalize() is a more general-purpose way for a single object of any type to clean up after itself.


Painting is how an applet actually draws something on the screen, be it text, a line, a colored background, or an image. Painting can occur many thousands of times during an applet's life cycle (for example, after the applet is initialized, if the browser is placed behind another window on the screen and then brought forward again, if the browser window is moved to a different position on the screen, or perhaps repeatedly, in the case of animation). You override the paint() method if your applet needs to have an actual appearance on the screen (that is, most of the time). The paint() method looks like this:

public void paint(Graphics g) {

Note that unlike the other major methods in this section, paint() takes an argument, an instance of the class Graphics. This object is created and passed to paint by the browser, so you don't have to worry about it. However, you will have to make sure that the Graphics class (part of the java.awt package) gets imported into your applet code, usually through an import statement at the top of your Java file:

import java.awt.Graphics;

A Simple Applet

Way back on Day 2, "Object-Oriented Programming and Java," you created a simple applet called HelloAgainApplet (this was the one with the big red Hello Again). There, you created and used that applet as an example of creating a subclass. Let's go over the code for that applet again, this time looking at it slightly differently in light of the things you just learned about applets. Listing 8.1 shows the code for that applet.

Listing 8.1. The Hello Again applet.
 1:  import java.awt.Graphics;
 2:  import java.awt.Font;
 3:  import java.awt.Color;
 5:  public class HelloAgainApplet extends java.applet.Applet {
 7:     Font f = new Font("TimesRoman", Font.BOLD, 36);
 9:     public void paint(Graphics g) {
10:        g.setFont(f);
11:        g.setColor(Color.red);
12:        g.drawString("Hello again!", 5, 40);
13:     }
14: }

This applet implements the paint() method, one of the major methods described in the previous section (actually, it overrides the default implementation of paint(), which does nothing). Because the applet doesn't actually do much (all it does is print a couple words to the screen), and there's not really anything to initialize, you don't need a start(), stop(), init(), or destroy() method.

The paint method is where the real work of this applet (what little work goes on) really occurs. The Graphics object passed into the paint() method holds the graphics state for the applet-that is, the current features of the drawing surface, such as foreground and background colors or clipping area. Lines 10 and 11 set up the font and color for this graphics state (here, the font object held in the f instance variable, and a Color object representing the color red).

Line 12 draws the string "Hello Again!" by using the current font and color at the position 5, 40. Note that the 0 point for x, y is at the top left of the applet's drawing surface, with positive y moving downward, so 50 is actually at the bottom of the applet. Figure 8.1 shows how the applet's bounding box and the string are drawn on the page.

Figure 8.1 : Drawing the applet.

If you've been following along with all the examples up to this point, you might notice that there appears to be something missing in this class: a main() method. As mentioned in the section on the differences between applets and applications, applets don't need a main() method. By implementing the right applet methods in your class (init(), start(), stop(), paint(), and so on), your applet just seamlessly works without needing an explicit jumping-off point.

Including an Applet on a Web Page

After you create a class or classes that contain your applet and compile them into class files as you would any other Java program, you have to create a Web page that will hold that applet by using the HTML language. There is a special HTML tag for including applets in Web pages; Java-enabled browsers use the information contained in that tag to locate the compiled class files and execute the applet itself. In this section, you'll learn about how to put Java applets in a Web page and how to serve those files to the Web at large.

The following section assumes that you have at least a passing understanding of writing HTML pages. If you need help in this area, you may find the book Teach Yourself Web Publishing with HTML in 14 Days useful. It is also from Sams.net and also by Laura Lemay, the author of much of this book.

The <APPLET> Tag

To include an applet on a Web page, use the <APPLET> tag. <APPLET> is a special extension to HTML for including applets in Web pages. Listing 8.2 shows a very simple example of a Web page with an applet included in it.

Listing 8.2. A simple HTML page.
 1:  <HTML>
 2:  <HEAD>
 3:  <TITLE>This page has an applet on it</TITLE>
 4:  </HEAD>
 5:  <BODY>
 6:  <P>My second Java applet says:
 7:  <BR><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50>
 8:  Hello Again!
 9:  </APPLET>
10:  </BODY>
11:  </HTML>

There are three things to note about the <APPLET> tag in this page:

Note that the <APPLET> tag, like the <IMG> tag itself, is not a paragraph, so it should be enclosed inside a more general text tag, such as <P> or one of the heading tags (<H1>, <H2>, and so on).

Testing the Result

Now with a class file and an HTML file that refers to your applet, you should be able to load that HTML file into your Java-enabled browser from your local disk (in Netscape, use Open File from the File menu; in Internet Explorer, use Open from the File menu and then choose Browse to find the right file on your disk). The browser loads and parses your HTML file, and then loads and executes your applet class.

If you don't have a Java-enabled browser, there are often tools that come with your development environment to help you test applets. In the JDK, the appletviewer application will test your applets. You won't see the Web page the applet is running on, but you can figure out if the applet is indeed running the way you expect it to.

Figure 8.2 shows the Hello Again applet running in Netscape.

Figure 8.2 : The Hello Again applet.

Making Java Applets Available to the Web

After you have an applet and an HTML file, and you've verified that everything is working correctly on your local system, the last step is to make that applet available to the World Wide Web at large so that anyone with a Java-enabled browser can view that applet.

Java applets are served by a Web server the same way that HTML files, images, and other media are. You don't need special server software to make Java applets available to the Web; you don't even need to configure your server to handle Java files. If you have a Web server up and running, or space on a Web server available to you, all you have to do is move your HTML and compiled class files to that server, as you would any other file.

If you don't have a Web server, you have to rent space on one or set one up yourself. (Web server setup and administration, as well as other facets of Web publishing in general, are outside the scope of this book.)

More About the <APPLET> Tag

In its simplest form, by using CODE, WIDTH, and HEIGHT, the <APPLET> tag merely creates a space of the appropriate size and then loads and runs the applet in that space. The <APPLET> tag, however, does include several attributes that can help you better integrate your applet into the overall design of your Web page.

The attributes available for the <APPLET> tag are almost identical to those for the HTML <IMG> tag.


The ALIGN attribute defines how the applet will be aligned on the page. This attribute can have one of nine values: LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, or ABSBOTTOM.

In the case of ALIGN=LEFT and ALIGN=RIGHT, the applet is placed at the left or right margin of the page, respectively, and all text following that applet flows in the space to the right or left of that applet. The text will continue to flow in that space until the end of the applet, or you can use a line break tag (<BR>) with the CLEAR attribute to start the left line of text below that applet. The CLEAR attribute can have one of three values: CLEAR=LEFT starts the text at the next clear left margin, CLEAR=RIGHT does the same for the right margin, and CLEAR=ALL starts the text at the next line where both margins are clear.

In Netscape Navigator for Windows, the use of the ALIGN attribute prevents the applet from actually being loaded (this is a bug; it works fine in the UNIX and Macintosh versions of Netscape, as well as in Internet Explorer). If you're using alignment extensively in your Web pages with applets, you might want to enclose them in tables and align the tables themselves rather than use ALIGN.

For example, here's a snippet of HTML code that aligns an applet against the left margin, has some text flowing alongside it, and then breaks at the end of the paragraph so that the next bit of text starts below the applet:

<P><APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50
To the left of this paragraph is an applet. It's a
simple, unassuming applet, in which a small string is
printed in red type, set in 36 point Times bold.
<P>In the next part of the page, we demonstrate how
under certain conditions, styrofoam peanuts can be
used as a healthy snack.

Figure 8.3 shows how this applet and the text surrounding it might appear in a Java-enabled browser (I've lightened the default page background so you can see where the applet begins and the background ends).

Figure 8.3 : An applet aligned left.

For smaller applets, you might want to include your applet within a single line of text. To do this, there are seven values for ALIGN that determine how the applet is vertically aligned with the text:

Figure 8.4 shows the various alignment options, where the line is an image and the arrow is a small applet.

Figure 8.4 : Applet alignment options.


The HSPACE and VSPACE attributes are used to set the amount of space, in pixels, between an applet and its surrounding text. HSPACE controls the horizontal space (the space to the left and right of the applet). VSPACE controls the vertical space (the space above and below). For example, here's that sample snippet of HTML with vertical space of 50 and horizontal space of 10:

<P><APPLET CODE="HelloAgainApplet.class" WIDTH=300 HEIGHT=200
To the left of this paragraph is an applet. Its a
simple, unassuming applet, in which a small string is
printed in red type, set in 36 point Times bold.
<P>In the next part of the page, we demonstrate how
under certain conditions, styrofoam peanuts can be
used as a healthy snack.

The result in a typical Java browser might look like that in Figure 8.5.

Figure 8.5 : Vertical and horizontal space.


The final two attributes to note in <APPLET> are CODE and CODEBASE. Unlike the other attributes, neither of these has anything to do with the applet's appearance on the page; these two refer to the actual location of the Java applet file so that the Java-enabled browser can find it.

CODE is used to indicate the name of the class file that holds the current applet. If CODE is used alone in the <APPLET> tag, the class file is searched for in the same directory as the HTML file that references it. Note that class filenames used in CODE have the .class extension; this is different from in the Java command-line interpreter, which doesn't use the extension.

If you want to store your class files in a different directory on your Web server than that of your HTML files, you have to tell the browser where to find those class files. To do this, you use CODEBASE. CODE contains only the name of the class file; CODEBASE contains an alternate pathname (actually a URL or relative pathname) where classes are contained. For example, if you store your class files in a directory called classes, which is in the same directory as your HTML files, CODEBASE is the following:

<APPLET CODE="myclass.class" CODEBASE="classes"
    WIDTH=100 HEIGHT=100></APPLET>

If you store all your Java classes in some central location, you can also use a URL in CODEBASE:

<APPLET CODE="myclass.class" CODEBASE="http://myserver.com/javaclasses"
    WIDTH=100 HEIGHT=100></APPLET>

What if your class files are actually stored on an entirely different server altogether? You can use that URL in CODEBASE as well:

<APPLET CODE="myclass.class" CODEBASE="http://www.joesserver.com/javaclasses"
    WIDTH=100 HEIGHT=100></APPLET>

Java Archives

Normally, using the standard way of indicating Java applets in Web pages, you use <APPLET> to point to the primary applet class for your applet. Your Java-enabled browser will then download and run that applet. That applet may use other classes or media files, all of which are also downloaded from the Web server as they are needed.

The problem with running applets in this way is that every single file an applet needs-be it another helper class, image, audio file, text file, or anything else-is a separate connection the browser has to make to the server. Because there's a fair amount of time needed just to make the connection itself, this can increase the amount of time it takes to download your applet and everything it needs.

The solution to this problem is a Java archive. A Java archive is a collection of Java classes and other files contained in a single file. By using a Java archive, the browser only makes one connection to the server, rather than several. By reducing the number of files the browser has to load from the server, your applet can be downloaded and run that much faster. Java archives may also be compressed, making the overall file size smaller and therefore faster to download as well (although it may take some time on the browser side for the files to be decompressed before they can run).

Right now only Netscape supports the use of Java archives, and only for Java class files (not for media). Within Netscape, you can use the ARchIVE attribute to indicate the name of the archive, like this:

<APPLET CODE="MyApplet.class" ARchIVE="appletstuff.zip" WIDTH=100 HEIGHT=100>

The archive itself is an uncompressed zip file. Standard zip files, which use some form of compression to make the file smaller, are not recognized. Also, helper classes may be contained inside or outside the zip file; Netscape will look in either place.

The ARchIVE attribute is ignored by browsers or applet viewers that may run across this Web page. If you do use Java archives for Netscape, it's a good idea to store both the archive and the individual files on your Web server so that all the Java-enabled browsers who visit your Web page can view your applet.

In addition to Netscape's simple archive scheme, Java 1.1 will include support for JAR files. JAR files are Java archives, with or without compression, that can contain both classes and media. In addition, JAR files are platform independent, and the tools to create them will be available on any platform that supports the JDK. JAR files and their individual components can also be digitally signed, meaning that their creator can be reliably identified (a form of security). For more information about JAR files, including the specifications for the actual file format, see the JDK 1.1 Preview Page at http://java.sun.com/products/JDK/1.1/designspecs/.

Passing Parameters to Applets

With Java applications, you pass parameters to your main() routine by using arguments on the command line, or, for Macintoshes, in the Java Runner's dialog box. You can then parse those arguments inside the body of your class, and the application acts accordingly, based on the arguments it is given.

Applets, however, don't have a command line. How do you pass in different arguments to an applet? Applets can get different input from the HTML file that contains the <APPLET> tag through the use of applet parameters. To set up and handle parameters in an applet, you need two things:

Applet parameters come in two parts: a parameter name, which is simply a name you pick, and a value, which is the actual value of that particular parameter. So, for example, you can indicate the color of text in an applet by using a parameter with the name color and the value red. You can determine an animation's speed using a parameter with the name speed and the value 5.

In the HTML file that contains the embedded applet, you indicate each parameter using the <PARAM> tag, which has two attributes for the name and the value, called (surprisingly enough) NAME and VALUE. The <PARAM> tag goes inside the opening and closing <APPLET> tags:

<APPLET CODE="MyApplet.class" WIDTH=100 HEIGHT=100>
<PARAM NAME=font VALUE="TimesRoman">
<PARAM NAME=size VALUE="36">
A Java applet appears here.</APPLET>

This particular example defines two parameters to the MyApplet applet: one whose name is font and whose value is TimesRoman, and one whose name is size and whose value is 36.

Parameters are passed to your applet when it is loaded. In the init() method for your applet, you can then get hold of those parameters by using the getParameter() method. getParameter() takes one argument-a string representing the name of the parameter you're looking for-and returns a string containing the corresponding value of that parameter. (Like arguments in Java applications, all the parameter values are strings.) To get the value of the font parameter from the HTML file, you might have a line such as this in your init() method:

String theFontName = getParameter("font");

The names of the parameters as specified in <PARAM> and the names of the parameters in getParameter() must match identically, including having the same case. In other words, <PARAM NAME="name"> is different from <PARAM NAME="Name">. If your parameters are not being properly passed to your applet, make sure the parameter cases match.

Note that if a parameter you expect has not been specified in the HTML file, getParameter() returns null. Most often, you will want to test for a null parameter in your Java code and supply a reasonable default:

if (theFontName == null)
    theFontName = "Courier"

Keep in mind that getParameter() returns strings-if you want a parameter to be some other object or type, you have to convert it yourself. To parse the size parameter from that same HTML file and assign it to an integer variable called theSize, you might use the following lines:

int theSize;
String s = getParameter("size");
if (s == null)
    theSize = 12;
else theSize = Integer.parseInt(s);

Get it? Not yet? Let's create an example of an applet that uses this technique. You'll modify the Hello Again applet so that it says hello to a specific name, for example, "Hello Bill" or "Hello Alice". The name is passed into the applet through an HTML parameter.

Let's start by copying the original HelloAgainApplet class and calling it MoreHelloAgain (see Listing 8.3).

Listing 8.3. The More Hello Again applet.
 1:import java.awt.Graphics;
 2:import java.awt.Font;
 3:import java.awt.Color;
 5:public class MoreHelloApplet extends java.applet.Applet {
 7:    Font f = new Font("TimesRoman", Font.BOLD, 36);
 9:    public void paint(Graphics g) {
10:        g.setFont(f);
11:        g.setColor(Color.red);
12:        g.drawString("Hello Again!", 5, 40);
13:    }

The first thing you need to add to this class is a place to hold the name of the person you're saying hello to. Because you'll need that name throughout the applet, let's add an instance variable for the name, just after the variable for the font in line 7:

String name;

To set a value for the name, you have to get that parameter from the HTML file. The best place to handle parameters to an applet is inside an init() method. The init() method is defined similarly to paint() (public, with no arguments, and a return type of void). Make sure when you test for a parameter that you test for a value of null. The default, in this case, if a name isn't indicated, is to say hello to "Laura". Add the init() method in between your instance variable definitions and the definition for paint(), just before line 9:

public void init() {
    name = getParameter("name");
    if (name == null)
        name = "Laura";

Now that you have the name from the HTML parameters, you'll need to modify it so that it's a complete string-that is, to tack the word Hello with a space onto the beginning, and an exclamation point onto the end. You could do this in the paint() method just before printing the string to the screen, but that would mean creating a new string every time the applet is painted. It would be much more efficient to do it just once, right after getting the name itself, in the init() method. Add this line to the init() method just before the last brace:

name = "Hello " + name + "!";

And now, all that's left is to modify the paint() method to use the new name parameter. The original drawString() method looked like this:

g.drawString("Hello Again!", 5, 40);

To draw the new string you have stored in the name instance variable, all you need to do is substitute that variable for the literal string:

g.drawString(name, 5, 40);

Listing 8.4 shows the final result of the MoreHelloApplet class. Compile it so that you have a class file ready.

Listing 8.4. The MoreHelloApplet class.
 1:  import java.awt.Graphics;
 2:  import java.awt.Font;
 3:  import java.awt.Color;
 5:  public class MoreHelloApplet extends java.applet.Applet {
 7:     Font f = new Font("TimesRoman", Font.BOLD, 36);
 8:     String name;
10:     public void init() {
11:         name = getParameter("name");
12:         if (name == null)
13:             name = "Laura";
15:         name = "Hello " + name + "!";
16:     }
18:     public void paint(Graphics g) {
19:         g.setFont(f);
20:         g.setColor(Color.red);
21:         g.drawString(name, 5, 40);
22:     }
23: }

Now let's create the HTML file that contains this applet. Listing 8.5 shows a new Web page for the MoreHelloApplet applet.

Listing 8.5. The HTML file for the MoreHelloApplet applet.
 1:  <HTML>
 2:  <HEAD>
 3:  <TITLE>Hello!</TITLE>
 4:  </HEAD>
 5:  <BODY>
 6:  <P>
 7:  <APPLET CODE="MoreHelloApplet.class" WIDTH=200 HEIGHT=50>
 8:  <PARAM NAME=name VALUE="Bonzo">
 9:  Hello to whoever you are!
10: </APPLET>
11: </BODY>
12: </HTML>

Note the <APPLET> tag, which points to the class file for the applet and has the appropriate width and height (200 and 50). Just below it (line 8) is the <PARAM> tag, which you use to pass in the value for the name. Here, the NAME parameter is simply name, and the VALUE is the string "Bonzo".

Loading up this HTML file in Netscape produces the result shown in Figure 8.6.

Figure 8.6 : The result of using MoreHelloApplet the first time.

Let's try a second example. Remember that in the code for MoreHelloApplet, if no name is specified in a parameter, the default is the name Laura. Listing 8.6 creates an HTML file with no parameter tag for name.

Listing 8.6. Another HTML file for the MoreHelloApplet applet.
 1: <HTML>
 2: <HEAD>
 3: <TITLE>Hello!</TITLE>
 4: </HEAD>
 5: <BODY>
 6: <P>
 7: <APPLET CODE="MoreHelloApplet.class" WIDTH=200 HEIGHT=50>
 8: Hello to whoever you are!
 9: </APPLET>
10: </BODY>
11: </HTML>

Here, because no name was supplied, the applet uses the default, and the result is what you might expect (see Figure 8.7).

Figure 8.7 : The result of using MoreHelloApplet the second time.


Applets are probably the most common use of the Java language today. Applets are more complicated than many Java applications because they are executed and drawn inline within Web pages, but they can access the graphics, user interface, and event structure provided by the Web browser itself. Today you learned the basics of creating applets, including the following things:


In the first part of today's lesson, you say that applets are downloaded from random Web servers and run on the client's system. What's to stop an applet developer from creating an applet that deletes all the files on that system, or in some other way compromises the security of the system?
Recall that Java applets have several restrictions that make it difficult for all of the more obvious malicious behavior to take place. For example, because Java applets cannot read or write files on the client system, they cannot delete files or read system files that might contain private information. Because they cannot run programs on the client's system without your express permission, they cannot, for example, pretend to be you and run system programs. Nor can they run so many programs that your system crashes.

In addition, Java's very architecture makes it difficult to circumvent these restrictions. The language itself, the Java compiler, and the Java interpreter all have checks to make sure that no one has tried to sneak in bogus code or play games with the system itself. You'll learn more about these checks at the end of this book.

Of course, no system can claim to be 100 percent secure, and the fact that Java applets are run on your system should make you suspicious-see Day 21 for more on security.

Wait a minute. If I can't read or write files or run programs on the system the applet is running on, doesn't that mean I basically can't do anything other than simple animation and flashy graphics? How can I save state in an applet? How can I create, say, a word processor or a spreadsheet as a Java applet?
For everyone who doesn't believe that Java is secure enough, there is someone who believes that Java's security restrictions are too severe for just these reasons. Yes, Java applets are limited because of the security restrictions. But, given the possibility for abuse, I believe that it's better to err on the side of being more conservative as far as security is concerned. Consider it a challenge.

Keep in mind, also, that Java applications have none of the restrictions that Java applets do, but because they are also compiled to bytecode, they are portable across platforms. It may be that the thing you want to create would make a much better application than an applet.

If the thing you want to create has to be an applet, the only solution you have for saving state or implementing something like a word processor in a Java applet is to allow your readers to save the state back to your server.

Will applets be like this forever-confined to the sandbox and unable to do anything other than whizzy animation and simple toys?
Sun is working on future models for applet security that will allow applets to break out of the sandbox in some instances. One of the solutions being discussed is for the applet class file to be digitally signed, which is a way to identify without a doubt where an applet came from (for example, if an applet is signed by Sun, you can be sure it was Sun that actually created it, and therefore trust it more than some other random applet need). You'll learn more about applet security on Day 21.
I have an older version of the HotJava browser. I followed all the examples in this section, but HotJava cannot read my applets (it seems to ignore them). What's going on?
You most likely have an alpha version of HotJava. Recall that significant changes were made to the Java API and how Java applets are written between alpha and the 1.0 release. The result of these changes is that browsers that support alpha applets cannot read beta applets, and vice versa. The HTML tags are even different, so an older browser just skips over newer applets, and vice versa.

By the time you read this, there may be a new version of HotJava with support for 1.0. If not, you can use Netscape, Internet Explorer, or the JDK's appletviewer to view applets written to the beta specification.

I noticed in my documentation that the <APPLET> tag also has a NAME attribute. You didn't discuss it here.
NAME is used when you have multiple applets on a page that need to communicate with each other. You'll learn about this on Day 12, "Managing Simple Events and Interactivity."
Lots of the applet examples I've seen on the Web have an init() method that does nothing to call a resize() method with the same values as in the <APPLET> tag's WIDTH and HEIGHT. I asked a friend about that and he said that you have to have resize() in there to make sure the applet's the right size. You don't mention resize().
The call to the resize() method in init() is left over from the early days of applets when you did need resize() to set the initial size of the applet. These days only the WIDTH and HEIGHT attributes do that; calling resize() isn't necessary.
I have an applet that takes parameters and an HTML file that passes it those parameters. But when my applet runs, all I get are null values. What's going on here?
Do the names of your parameters (in the NAME attribute) match exactly with the names you're testing for in getParameter()? They must be exact, including case, for the match to be made. Make sure also that your <PARAM> tags are inside the opening and closing <APPLET> tags, and that you haven't misspelled anything.
Since applets don't have a command line or a stdout stream, how can you do simple debugging output like System.out.println() in an applet?
You can. Depending on your browser or other Java-enabled environment, there may be a console window where debugging output (the result of System.out.println()) appears, or it may be saved to a log file (Netscape has a Java Console under the Options menu; Internet Explorer uses a Java log file that you must enable using Options | Advanced). You can continue to print messages using System.out.println() in your applets-just remember to remove them once you're done so they don't confuse your actual readers!