Chapter 2

Running Java Applets


CONTENTS

Because you're interested in writing Java applets (you bought this book, after all), you're probably already pretty familiar with using HTML (Hypertext Markup Language) to create Web pages. If not, you should pick up a book on HTML and get some idea of how that markup language works. Even if you're an HTML expert, though, you may not have seen the HTML extension that Sun Microsystems created to support Java applets in Web pages. In this chapter, then, you not only get a chance to see Java applets up and running, but you also learn how to add them to your Web pages.

The Sample Java Applets

As you learned in Chapter 1 "Java Overview," the Java Developer's Kit (JDK) includes many sample applets that you can test in your Web pages. (The HotJava browser, too, comes with a few of these sample applets.) If you installed the JDK as described in Chapter 1 you're ready to start experimenting with Java applets. In this section, you will use the Appletviewer tool-which comes with the JDK-to get a quick look at some applets. A following section, "Adding Applets to an HTML Document," will show you how to add an applet to a Web page.

The Appletviewer Tool

The truth is that you can write and run applets without even having a Java-compatible browser. This is thanks to the Appletviewer tool that comes as part of the JDK. Appletviewer is a Windows application (unless you're using a non-Windows version of the JDK) that you run from a DOS command line. Part of the command line is the applet that you want to run. When Appletviewer appears, the applet appears in the viewer's main window.

To run the Appletviewer application, first bring up an MS-DOS window by selecting the MS-DOS Prompt command from Programs on the Start menu. Then, switch to the folder containing the applet you want to run and type the command line C:\JAVA\BIN\APPLETVIEWER DOC.htmL.

In the preceding command line, DOC.htmL is the name of an HTML document that contains the tag for the applet you want to see.

Example: Running TicTacToe

Suppose you want to run the TicTacToe demo applet that comes with the JDK. To do this, just follow these steps:

  1. Select the Start/Programs/MS-DOS Prompt command. The DOS window appears, as shown in Figure 2.1.
    Figure 2.1 : The first step in running Appletviewer is to bring up the MS-DOS window.

  2. Change to the directory containing the TicTacToe applet (Figure 2.2).
    Figure 2.2 : The second step is to change to the applet's directory.

  3. Type the command line C:\JAVA\BIN\APPLETVIEWER EXAMPLE1.htmL.The Appletviewer runs, loading and displaying the TicTacToe applet (Figure 2.3).
    Figure 2.3 : The requested applet appears in Appletviewer's main window.

Now that you have the applet started, try a few games of TicTacToe against the computer. To place an X, click the square you want. You'll quickly discover that the computer player is as dumb as yogurt. Let's just say that you don't have to be a rocket scientist to win (Figure 2.4).

Figure 2.4 : Beating this ver-sion of TicTacToe doesn't require a degree in computer science.

TIP
If you want to avoid typing the full path name for Appletviewer every time you run it, type the command PATH=C:\JAVA\BIN at the MS-DOS prompt to add Appletviewer's directory to your path. (Of course, if you've installed the JDK somewhere else on your hard drive, you'll have to use a different path in the command.) After you type this command, MS-DOS will be able to find Appletviewer without your having to type the full path. For example, you'll be able to run TicTacToe by switching to the TicTacToe directory and simply typing APPLETVIEWER EXAMPLE1.htmL. You can also add Appletviewer's path to the PATH statement in your AUTOEXEC.BAT file and thus avoid having to type it in by hand every time you start your system and want to use Appletviewer.

The Animator Applet

Another applet that demonstrates some interesting facets of Java programming is the Animator applet, which not only displays various animation sequences, but also plays sound effects simultaneously. To run the Animator applet, switch to the C:\JAVA\DEMO\ANIMATOR folder and type the command line APPLETVIEWER EXAMPLE1.htmL. (The previous command line assumes that you've set your path to the JAVA\BIN directory.) When you do, you see the display shown in Figure 2.5. (Yep, it's the ubiquitous Duke, waving at you from his very own applet.)

Figure 2.5 : The Animator applet includes several animation and sound examples, including this one featuring Duke, the Java mascot.

Animator is an example of a configurable applet. That is, by modifying the HTML tag that loads and runs the applet, the user can display his or her own custom animation sequence and sound effects. You'll learn about configurable applets in Chapter 26, "Configurable Applets." For now, though, it's enough for you to know that Java is capable of adding both animation sequences and sound effects to your Web pages.

NOTE
If you'd like to see what the applet's HTML tag looks like, select Appletviewer's Applet,Tag command.

The BarChart Applet

BarChart, another configurable applet, is especially useful when you need to graphically display data values in a Web page. To check out BarChart, switch to the JAVA\DEMO\BARCHART folder and type the command line APPLETVIEWER EXAMPLE1.htmL. When you do, you see the window shown in Figure 2.6.

Figure 2.6 : The BarChart applet enables you to create graphs in your Web pages.

Because BarChart is configurable, you can create all sorts of different bar charts in your Web pages just by specifying different parameters in the applet's HTML tag. As you can see, applets can be powerful tools for creating dynamic and useful Web pages. (Try out Appletviewer's Applet,Tag command to see the code that specifies how the bar chart appears.)

Other Demo Applets

The DEMO folder contains many sample applets that you can experiment with using Appletviewer. All of the demo applets are run from HTML documents with names such as EXAMPLE1.htmL, EXAMPLE2.htmL, and so on. All demo applets have at least the EXAMPLE1.htmL document, while others have additional examples. To run any demo applet, change to the applet's folder and type APPLETVIEWER EXAMPLE1.htmL (assuming that you've set your path to the Appletviewer application). Use the DIR command to display the contents of an applet's directory in order to discover whether the applet features additional example HTML files.

NOTE
Remember that the HotJava browser cannot load and run newer applets like those that come with the latest version of the JDK.

Adding Applets to an HTML Document

If you've created Web pages before, you know that you use HTML to create a template for the page. The commands in the template tell a Web browser how to display the Web page. When Sun Microsystems developed Java, they also had to come up with an extension to HTML that would enable Web pages to contain Java applets. That extension is the <applet> tag, which Sun Microsystems defines as shown in Listing 2.1.


Listing 2.1  LST2_1.TXT: The <applet> Tag Definition.

<applet attributes>

parameters

alternate-content

</applet>


In the preceding tag, the text in normal characters is typed literally; the text shown in italics is replaced by whatever is appropriate for the applet you're including in the document. As you can see, the <applet> tag is similar to other HTML tags with which you may be familiar. For example, the tag starts with <applet attributes> and ends with </applet>, which is not unlike the format of other HTML tags. The first and last lines are required. Other lines in the tag are optional.

The attributes section of the <applet> tag contains important information about the tag, including the associated .CLASS file and the applet's width and height. The last line tells the browser that it has reached the end of the tag. You can load and run the TicTacToe applet, for example, with the <applet> tag shown in Listing 2.2.


Listing 2.2  LST2_2.TXT: A Tag for Loading and Running TicTacToe.

<applet

    code=TicTacToe.class

    width=120

    height=120>

</applet>


In the preceding example, the code attribute is the name of the .CLASS file for the applet. If you remember, the .CLASS file holds the applet's byte-code representation, which can be run by the Java interpreter. The width and height attributes control the size of the applet.

The TicTacToe tag above is the simplest <applet> tag you can write. That is, the code, width, and height attributes are all required, as is the final </applet> line.

Optional Attributes for Applets

There are several optional attributes you can use with the <applet> tag. The first is codebase, which specifies the applet's base folder or URL (Uniform Resource Locator). This folder or URL is used in combination with the file specified in the code attribute to find the applet's code. In the case of a folder, the codebase attribute is relative to the location of the HTML document containing the applet's tag. In Listing 2.2, because the codebase attribute is missing, the Web browser will look for the applet's files in the same folder as the HTML document. The <applet> tag in Listing 2.2 looks like Listing 2.3 when using the codebase attribute. (Don't try to use run this HTML code, as it's only an example of the attribute's format and may not run.)


Listing 2.3  LST2_3.TXT: Using the codebase Attribute.

<applet

    codebase=tictactoe

    code=TicTacToe.class

    width=120

    height=120>

</applet>


The preceding tag tells the browser that the TicTacToe.class file is located in a folder called TICTACTOE. This folder must be on the same level in the directory tree as the HTML file. That is, if the HTML file is in the folder JAVA\DEMO, then the path for the .CLASS file should be JAVA\DEMO\TICTACTOE\TicTacToe.class. You can also use an URL, such as http://www.provider.com/my_pages/tictactoe, for the codebase attribute. This causes the applet to be loaded from the specified site.

Other optional attributes you can use with the <applet> tag are alt, align, name, hspace, and vspace. The alt attribute enables you to specify text that will be displayed by text-only browsers, whereas the name attribute gives the applet a symbolic name that's used to reference the applet (used when you need to communicate between applets).

The align, hspace, and vspace attributes all work together to position the applet within the text flow of the HTML document. These attributes work exactly as they do with the <img> tag that's used to display images in Web pages. The align attribute can be one of these values: left, right, middle, absmiddle, bottom, absbottom, baseline, top, or texttop. The hspace and vspace attributes control the amount of white space around the applet when align is set to left or right.

Listing 2.4 shows the script for a simple Web page using the <applet> tag. Figure 2.7 shows Netscape Navigator 2.0 displaying the page.

Figure 2.7 : This is the Web page created by Listing 2.4.


Listing 2.4  LST2_4.TXT: A Simple HTML Document Using the <applet> Tag.

<title>TicTacToe</title>

<hr>

This is a bunch of text whose sole purpose is to demonstrate

the placement

<applet

    codebase=TicTacToe

    code=TicTacToe.class

    width=120

    height=120

    alt="This is the TicTacToe applet."

    name=TicTacToe

    align=middle>

</applet> 

of the TicTacToe applet within the text flow of an HTML document.

<hr>


TIP
To load an HTML document into Netscape Navigator 2.0, select the File, Open File command or press Ctrl+O. Then select the file in the dialog box that appears.

Applet Parameters

As you know, many Java applets are configurable, meaning that the applet user can specify certain values that the applet will use when it starts. A good example is the BarChart applet you saw earlier in this chapter. When you need to specify parameters for an applet, you use the <param> tag. The <param> tags, one for each parameter you want to set, are placed after the starting <applet> tag and before the ending </applet> tag. For example, Listing 2.5 shows parameters being set for the BarChart applet. Figure 2.8 shows the resultant bar chart. As you can see from the listing, each parameter has two parts, the parameter name and the value to which it should be set. You'll learn more about applet parameters in Chapter 26, "Configurable Applets."

Figure 2.8 : This is the bar chart created by the parameters in Listing 2.5.


Listing 2.5  LST2_5.TXT: Using Parameters with Applets.

<applet

    code="Chart.class"

    width=251

    height=125>

<param name=title value="Sales">

<param name=orientation value="vertical">

<param name=scale value="5">

<param name=columns value="3">

<param name=c1_style value="solid">

<param name=c1 value="10">

<param name=c1_color value="blue">

<param name=c1_label value="Jan">

<param name=c2_style value="solid">

<param name=c2 value="12">

<param name=c2_color value="green">

<param name=c2_label value="Feb">

<param name=c3_style value="solid">

<param name=c3 value="15">

<param name=c3_color value="red">

<param name=c3_label value="Mar">

</applet>


Non-Java Browsers

You may wonder what happens when a browser that's not Java-compatible finds an applet in an HTML document. In this case, as is standard behavior for browsers, the non-Java browser simply ignores the tags it doesn't recognize. However, you may want to provide a more user-friendly response to users who are trying to view your applets with non-Java browsers. You can do this easily by placing alternate content right before the ending </applet> tag. Listing 2.6, for example, shows the HTML script for running the TicTacToe applet with alternate content for browsers that don't support Java.


Listing 2.6  LST2_6.TXT: Supplying Alternate Content for TicTacToe.

<applet

    code=TicTacToe.class

    width=120

    height=120>

<b>If you had a Java-compatible browser,

you'd be playing TicTacToe right now!</b>

</applet>


The alternate content you provide can comprise any standard HTML commands and is ignored by Java-compatible browsers. That is, the alternate content appears only in non-Java browsers.

Example: A Java-Powered Home Page

In the previous section, you saw a sample HTML document that contains an applet. You also saw what this document looks like when loaded into Netscape Navigator 2.0. Now you'll use what you've learned to create your own "appletized" home page for Netscape Navigator. To do this, you must first write your home page's HTML file. Then you must set Netscape Navigator's home-page property, which determines the document the browser displays at startup. Just follow the steps below to accomplish these tasks:

  1. Create a folder called HOMEPAGE in your C: drive's root directory.
  2. Type Listing 2.7 and save it as an ASCII file called HOMEPAGE.htmL in your HOMEPAGE directory. (If you don't want to type the listing, just copy it from the CHAP02 directory of this book's CD-ROM.)
  3. Copy the entire TICTACTOE folder (not just the folder's contents) from your JAVA\DEMO folder to your HOMEPAGE folder.
  4. Start up Netscape Navigator 2.0, and click Navigator's Stop button to stop loading the currently set home page.
  5. Select Options, General Preferences from Navigator's menu bar. The Preferences property sheet appears (Figure 2.9).
    Figure 2.9 : You can set your own starting home page in Navigator's Preferences property sheet.

  6. Enter C:\HOMEPAGE\HOMEPAGE.htmL into the Start With text box.
  7. Click the Home button to load your new TicTacToe home page (Figure 2.10).
    Figure 2.10 : Here's your new TicTacToe home page, up and running.


Listing 2.7  HOMEPAGE.htmL: An HTML Script for a Home Page.

<title>My Home Page</title>

<h1>The TicTacToe Home Page</h1>

This may be a dumb home page, but it gives

you a chance to play the TicTacToe applet

every time you start Netscape Navigator 2.0!<h>

<hr>

<applet

    codebase=TicTacToe

    code=TicTacToe.class

    width=120

    height=120

    alt="This is the TicTacToe applet."

    name=TicTacToe>

</applet>

<hr>


TIP
When running under Netscape Navigator 2.0, the TicTacToe applet seems to respond slowly to mouse clicks at first. If the applet doesn't respond right away, try moving your mouse pointer off the applet. This trick wakes things up most of the time.

Summary

As you learned in this chapter, Java applets are relatively easy to add to your HTML documents. However, folks without Web browsers aren't completely left out of the fun. They can create and view applets using the handy Appletviewer application that comes as part of the JDK. Because HTML was designed long before there were Java applets, Sun Microsystems had to create an extension to HTML in order to accommodate applets in Web pages. The extension takes the form of the <applet> tag, which enables you to not only provide values for an applet's attributes, but also to include a list of parameters and even offer alternate content for non-Java browsers.

Review Questions

  1. How can someone without a Java-compatible browser run applets?
  2. What are the three required attributes for the <applet> tag?
  3. What does the optional codebase attribute do?
  4. Name two other optional applet attributes.
  5. Why would you use parameters with an applet?
  6. How can your applet-enhanced HTML documents accommodate non-Java browsers?

Review Exercises

  1. Use Appletviewer to view the BouncingHeads applet (or any other demo applet in which you're interested).
  2. Change the size of the BarChart applet in the HTML code from Listing 2.5.
  3. Modify the home page you created earlier in this chapter so that it displays both the NervousText and TicTacToe demo applets. The code for NervousText is found in the file NervousText.class. In addition to the applet's standard attributes, you'll also need to include one parameter called text, whose value is the text you want displayed.