Chapter 15

Creating Java-Powered Web Presentations with Applets


CONTENTS


Applets are a driving force behind Java's widespread popularity. The World Wide Web and Java can help you reach a global audience of millions, yet before anyone can preview your dazzling new applets you must create a document that showcases what you've done. To do this, you use the Hypertext Markup Language (HTML) and Java-specific markup tags.

Although this chapter discusses HTML and HTML document structure, the focus is on using the unique Java-specific markup tags. You will use these tags to add applets to sample HTML documents in creative and powerful ways, and ultimately to create a Web presentation. After creating a Java-powered presentation, you will need to publish it on the Web. Enjoy this part, because this is when you get to show the world your work.

Basic HTML Document Structure

Many books have been written on the subject of HTML, and I recommend you buy a couple of them. It is not my intent to describe the creation of the more intricate documents that can be produced with HTML, but rather to show only the necessary steps to get a Web browser to display an HTML document.

Understanding URLs

The first thing to know about HTML is how to read a Uniform Resource Locator, or URL (pronounced you-are-el). URLs are the addresses of Internet resources and are used by the Web browser to find Web publications, sounds, graphics, and applets. The first part of a URL contains the information necessary to determine the protocol required to access and transfer the resource.

A protocol you may be familiar with is the Hypertext Transfer Protocol (HTTP). As discussed in Chapter 3, "The Java Browser and the World Wide Web: A Primer," HTTP is used to transfer Web documents. After the protocol specification, the URL lists the address of the resource, beginning with the Internet host and domain names. For example, look at the following URL, which specifies a hypertext document called index.html on JavaSoft's Web server:

HTTP://java.sun.com/applets/index.html

URLs follow this general pattern. Some contain a listing of directories and subdirectories, separated by slash marks, before the actual resource is named. No matter how long the URL is, the protocol is the first item and the actual resource is the last item. Everything between the protocol and the resource is the listing of the hostname followed by the directory path that leads to the resource.

You will need this basic understanding of how URLs work a little later in this chapter. After you have composed the HTML document and prepared the applet to be loaded onto a Web server, you will determine the URL where the Web publication will reside. When you know the URL, you can let others know where to find your page.

Introduction to HTML Tags

HTML provides Web browsers with information for formatting text, graphics, and other multimedia objects by using markup tags. Tags define the structure of HTML documents and include an element name enclosed by brackets-for example, <P>, which indicates a new paragraph.

Most tags are used in pairs. The begin tag tells the browser a document element is beginning, and the end tag tells the browser an element is ending. The only difference between the two is that the end tag contains a forward slash before the element name. For example, the begin document tag <HTML> is paired with the end document tag </HTML>.

Because HTML tags are based on standard ASCII text, all you need to create HTML documents is a text editor or word processor. You save your HTML documents as standard ASCII text with the .htm or .html extension.

Tip
As you create your first Web page, keep in mind that ASCII text formatting is usually ignored by Web browsers. When your browser sees formatting such as tabs, spaces, paragraph returns, and page breaks-no matter how many times you repeat them-it interprets them as a single space. This primarily is because browsers rely on the HTML markup to specify the format of the page.

Although HTML is not case sensitive, it is important to use a consistent case in your tags. To clearly separate tags from text, it is a good practice to use either all uppercase or all lowercase and stick with it throughout the document. This is also important if you intend to use one of the many HTML editors available-they insert tags that are either all lowercase or all uppercase but do not mix the two in any single document.

The Header of an HTML Document

After the begin document tag <HTML>, the next tag to go into a Web page is the begin header tag, <HEAD>. This tag specifies the beginning of the document's header section and is used in a pair with the end header tag, </HEAD>. Although the HTML specification lists many tags for document headers, most document headers contain only a document title and its corresponding tags.

You specify the document title with the <TITLE> tag, which, with its corresponding end tag </TITLE>, should surround a well-thought-out title for your document. The title is significant because most Web browsers display the title prominently on their title bar. Browsers also store the title when readers save the location of the page as a bookmark or hotlist item. Both of these examples are good reasons for keeping the title as short and concise as possible. However, the title still must help the reader remember what it was about the page that caused him to mark its place. Other points to remember about the title are that there can be only one in each document and that it can contain only plain text.

The first Web presentation you will create in this chapter is for the RGB2Hex converter. Therefore, a good title might be something like the following:

<TITLE> RGB to Hex Converter </TITLE>

The title is short and to the point, but it clearly defines what the page contains. Having completed the header, you now must construct the body of the document.

The Body of an HTML Document

The document body begins with the next tag needed for defining the document structure, the body tag <BODY>. The remainder of the document, including all text, pictures, links, forms, tables, and Java applets, is contained within the begin and end tags in this pair. Your HTML document at this point should look like this:

<HTML>
<HEAD>
<TITLE> RGB to Hex Converter </TITLE>
</HEAD>
<BODY>
. . .
</BODY>
</HTML>

Now that you have defined the basic document structure, you can add some features, such as headings that will be centered in the browser window. To center headings, use the center tag, <CENTER>, or add the attribute ALIGN=CENTER to the heading tag. Although the current HTML specification does not provide many options for allowing the document writer to perform true page layout, HTML does provide tags like these to help with the presentation.

Peter's Principle
The nice thing about the <CENTER> tag is that it is not just for headings. The tag can be used anywhere in the body of the document when you want text, graphics, or other multimedia objects to be centered in the browser window. The bad thing about the <CENTER> tag is that it is nonstandard HTML markup used by the Netscape Navigator browser or other browsers capable of using Netscape extensions to HTML. For this reason, I prefer to use the ALIGN attribute with the heading tags when I want to center text.

The heading tags come in six levels: <H1> through <H6>. The higher the number, the smaller the font size used in the heading. Heading tags are always used in pairs, meaning the <H1> tag specifies the beginning of a level-1 heading and the </H1> tag specifies the end of a level-1 heading.

In the RGB2Hex document, you will use the <H2> and <H3> heading tags. The text between the opening and ending heading tags can be of any length and can include multiple lines. This does not, however, mean that the header should be of great length. Looking at line after line of emphasized text can become annoying very quickly. Use the heading tags as titles for paragraphs or marquee signs for pictures, forms, tables, and applets. You can add the ALIGN attribute to any heading tag, as in the following:

<H1 ALIGN=CENTER> Heading text to center </H1>

To further enhance the appearance of the document, you can add horizontal rules, which are great for showing clear separation between headings and text or between different sections contained in a document. The tag for the horizontal rule is simply <HR> and is one of the few tags that does not require an ending tag. For each <HR> tag used, a single horizontal rule that extends the width of the page is produced. Inserting multiple adjacent <HR> tags will produce a double- or triple-line effect.

At this point the HTML document looks like this:

<HTML>
<HEAD>
<TITLE> RGB to Hex Converter </TITLE>
</HEAD>
<BODY>
<CENTER>
<H2> The RGB to Hex Converter </H2>
<H3> Written with JAVA <H3>
<HR>
</BODY>
</HTML>

Now that you have a document for presentation on the World Wide Web, you need to mesh together the document and the Java applet. To do so, you use the Java extensions to HTML, which are described in the next section of this chapter. These extensions are really just more tags that define for the browser what to look for, where to find the code for the applet, and how to display the applet when it is loaded. Although not all the Java extensions are exclusive to Java, they are included because of their usefulness in displaying an applet. When you finish the next section, the RGB2Hex applet will be an integral part of your Web page.

The Java Extensions to HTML

The APPLET and PARAM elements comprise what I refer to collectively as the Java extensions to HTML. I refer to them this way because they work much the same way that other extensions, such as Netscape's, have in the past-that is, they add to the value of the current HTML specifications. When the HTML 3.2 draft specification was released in May 1996, the APPLET and PARAM elements officially became a part of the HTML standard. HTML 3.2 is the next evolution of the Hypertext Markup Language and is designed to replace HTML 2.0.

You will find that the APPLET and PARAM elements have many attributes that serve different purposes, and that not all of them are required for each applet. Indeed, do not attempt to use all these attributes in every single instance of these elements. Trying to use all the Java extensions will only cause clutter and confusion if they serve no true purpose.

The following sections describe the attributes of the APPLET and PARAM elements and when it is appropriate to use each attribute.

The APPLET Element

When Java was first introduced, the APP element was added to HTML to indicate a Java applet. Recently, the APPLET element has taken its place, and with it came many changes. Most of these are subtle, so if you were writing Java code before the change you should have no problem picking them up. If you were not, forget that the APP element ever existed and just learn the APPLET element.

The APPLET element is similar to the former APP element in that it contains some required attributes and includes optional attributes. One major difference is that the APPLET element now has an opening tag <APPLET> and an ending tag </APPLET>. The updated HTML document that contains the APPLET element with the required fields is as follows:

<HTML>
<HEAD>
<TITLE> RGB to Hex Converter </TITLE>
</HEAD>
<BODY>
<CENTER>
<H2> The RGB to Hex Converter </H2>
<H3> Written with JAVA <H3>
<HR>
<APPLET CODE="RGB2Hex" WIDTH=300 HEIGHT=300>
</APPLET>
</CENTER>
</BODY>
</HTML>

Inside the APPLET element are the required attributes CODE, WIDTH, and HEIGHT. The CODE attribute has taken the place of the CLASS attribute found in the APP element. The CODE attribute is a required because it gives the name of the file that contains the applet's compiled Applet subclass. The CODE attribute is absolute and can contain only the filename for the applet, not a path to a filename. If the applet code resides in a directory other than the one the HTML document is in, the APPLET element must include the optional attribute CODEBASE to indicate the path to the applet.

The WIDTH and HEIGHT attributes define the initial width and height of the applet display area. The unit of measurement used by these attributes is the pixel. Remember that not everyone uses the same display resolution for their monitors; what may appear to be a large applet at a display resolution of 640¥480 may appear small at 1024¥768. However, it is impossible to account for every possibility.

Another important point to remember is that these attributes define only the initial display area for the applet and not any windows or dialog boxes that the applet might bring up. Now that you've learned about all the required attributes of the APPLET element, let's look at each of the optional attributes.

Tip
You may find some applets that do not work with your Web browser. In all probability these applets will conform to the 1.0 Alpha API instead of API versions 1.0 and later that are reviewed in this chapter. Here is a quick conversion chart for rewriting these applets to conform to the current API:
1. Replace the APP element with the APPLET element.
2. Replace the CLASS attribute with the CODE attribute.
3. Replace the SRC attribute with the CODEBASE attribute.
4. ALIGN attribute remains.
5. HEIGHT and WIDTH attributes remain.
6. Place applet-specific attributes into <PARAM> tags.

If you know HTML or have published HTML documents, you may be wondering why the Java extensions specify begin and end APPLET tags. After all, all the necessary instructions are in the begin applet tag, <APPLET>, which makes the end APPLET tag seem unnecessary. Indeed, most Web publishers don't know why there are begin and end APPLET tags and don't place anything between them.

Between the begin and end APPLET tags, you can define an area of the document that will be displayed by browsers that are not capable of using Java applets. For example, if your applet is an animation, you can place an image reference in this area to allow readers who don't have Java-capable browsers to see something other than empty space. All Java-enhanced pages should contain a fully defined area of text, multimedia objects, and markup for such browsers. This will greatly expand the available audience for your Web presentations.

The HTML document you are creating can be extended using this concept, as shown in Listing 15.1. Readers who have a Java-capable browser see the RGB2Hex applet. Readers who don't see an image called RGB2Hex.gif and a message that tells them about the applet shown in the image. Figure 15.1 shows the document as displayed by a Web browser that cannot run Java applets.

Figure 15.1 : Defining making for users without Java-capable browsers.


Listing 15.1. Extending the document for wider audiences.
<HTML>
<HEAD>
<TITLE> RGB to Hex Converter </TITLE>
</HEAD>
<BODY>
<CENTER>
<H2> The RGB to Hex Converter </H2>
<H3> Written with JAVA <H3>
<HR>
<APPLET CODE="RGB2Hex" WIDTH=300 HEIGHT=300>
<IMG SRC="RGB2Hex.gif">
<BLOCKQUOTE>
The screenshot shows the RGB2Hex applet programmed in the Java
programming language. This applet lets you convert RGB color
values to hexadecimal values and see the corresponding color output.
</BLOCKQUOTE>
</APPLET>
</CENTER>
</BODY>
</HTML>

Optional Attributes for the APPLET Element

The optional attributes are every bit as important as the required ones. These attributes allow for much greater freedom in the use of applets and the layout of the Web presentation. This section reviews each optional attribute and gives details of how it is used.

ALIGN

Another feature that illustrates the attention to detail in the Java HTML extensions is the ALIGN attribute, which defines the alignment of the applet. Each of the possible values causes the applet or the text around it to line up differently. These values are the same as those for the <IMG> tag used for displaying images in HTML, as you can see from the following list:

Note
The value ALIGN=BASELINE was introduced by Netscape Navigator. Although it is interchangeable with the value ALIGN=BOTTOM, the developers of Netscape felt the word BASELINE was a better description of the way the text would be aligned.

The ALIGN attribute determines how the text is arranged with regard to the applet, but it does not determine how much space there will be between the text and the applet. To adjust the whitespace around the applet, you use the VSPACE and HSPACE attributes.

HSPACE and VSPACE

The HSPACE and VSPACE attributes let you define, in pixels, the amount of whitespace around the applet. VSPACE defines the vertical space above and below the applet, and HSPACE defines the horizontal space on either side of the applet. These attributes also work the same as those used for the <IMG> tag in HTML and are used like the WIDTH and HEIGHT attributes. To have five pixels of space around the applet, you would use HSPACE=5 and VSPACE=5 in the <APPLET> tag.

These are all the attributes that affect how the applet will be displayed on the page. The next attribute is useful only when the applet cannot be displayed on the page.

Tip
Although the ALIGN, VSPACE, and HSPACE attributes are listed in the JDK, none of them seem to have been fully incorporated into Java-enabled Web browsers as of this writing. The ALIGN values MIDDLE, TOP, TEXTTOP, ABSMIDDLE, BASELINE, BOTTOM, and ABSBOTTOM do work, but the LEFT, RIGHT, and CENTER attributes did not at this writing. A practical workaround for this is to include a new paragraph tag (<P>) before each instance of an applet. Inside the braces of the new paragraph tag alignment, you can include instructions for the paragraph. <P ALIGN=RIGHT> will cause everything between it and the </P> tag to align to the right margin of the document. Likewise, everything between a <P ALIGN=CENTER> tag and its ending </P> tag will be center justified. A description of these attributes is provided here in expectation that they will be incorporated into Web browsers in the near future.

ALT

When you try to load a Java-enhanced document into a browser that does not support Java, the applet will not be displayed. One alternative to a blank space in your page may be the alternative text (or ALT) attribute. Using the ALT attribute, you can define alternative text to display when the browser recognizes the <APPLET> tag but is not capable of running applets. In the <APPLET> tag, the ALT attribute is used in this manner:

<APPLET CODE="RGB2Hex" WIDTH=300 HEIGHT=300
ALT="This JAVA applet is a utility to convert RGB
input to Hex values.">

Currently, this attribute is of dubious value solely because all Web browsers that recognize the <APPLET> tag also automatically run Java applets. However, the HTML 3.2 specification includes the <APPLET> tag, which means that browsers that claim to support HTML 3.2 must also support the <APPLET> tag. Although these browsers may support HTML 3.2, they will not necessarily support Java.

CODEBASE

The optional attribute CODEBASE, mentioned previously, can be used in any HTML document to direct the Web browser to look for an applet located someplace other than the current directory without changing the current URL being viewed on the Web browser. With CODEBASE, anyone can use an applet stored elsewhere. This could be important to someone who is allotted only a few megabytes of storage space on his server, or perhaps to development teams that use separate servers and want to save time by not having to transfer files before use.

If the applet's compiled Applet subclass resides anywhere other than the base document URL, CODEBASE is needed to load the applet. CODEBASE is used to give the URL of the applet because the CODE attribute is absolute and can contain only the name of the Applet subclass. When CODE is used without CODEBASE, the document's base URL is used.

A simple way to think of this is that if you use CODEBASE, you can tell the Web browser where to look for the applet; otherwise, the browser looks in the current directory. Thus, using CODEBASE, you can run an applet stored on a different server or in a different directory than your Web presentation.

CODEBASE is also valuable in that it assists in organization of the Web site and frees Java programmers from ties to a single directory, such as the cgi-bin directory normally used for CGI scripts. Creating subdirectories in your Web publication directory for applets can help you stay organized. In this way, Java applets can reside in their own directory, or applets for a particular page can be grouped into a directory on the basis of where they are used. CODEBASE enables an HTML document to refer to these directories without having to use a document located in the same directory as the applet. Attention to little details such as this is one reason for Java's popularity.

NAME

Another means of identifying an applet is the NAME attribute. It plays a key role in how applets interact with other applets on the same Web page. By naming an applet, you can target it from other applets on the page, which makes it possible for applets on the same page to find and communicate with each other. If, for example, a user activates one of three applets on a page and all three applets are named with the NAME attribute, the active applet can pass values to the other two applets that cause them to behave in new ways, display new images and text, or even start a new animation sequence.

The NAME attribute is also included in the braces of the <APPLET> tag. An example follows:

<APPLET CODEBASE="http://tvp.com/applets/HyperText"
CODE="NervousText" WIDTH=400 Height=75 ALIGN=middle NAME=appletA>
</APPLET>
<APPLET CODEBASE="http://java.sun.com/applets/applets/NervousText"
CODE="NervousText" WIDTH=400 Height=75 ALIGN=middle NAME=appletB>
</APPLET>

In this example, appletA can communicate with appletB. When message passing is used for communication in Java applets, using the correct name for the applet is important to ensure that messages go to their correct destination. The name of the destination can be passed to the sender as a parameter using the PARAM element (described next).

The PARAM Element

The PARAM element is used to pass general-purpose parameters to an applet. Without it, applets could not communicate with each other, and you could not pass general-purpose values to applets. This section looks at how parameters are referenced in HTML documents and Java code.

Parameters Referenced in HTML Documents

The PARAM element is one of the few elements in HTML that uses only a begin tag. You place the begin tag, <PARAM>, between the opening and ending <APPLET> tags. This is the only element between the APPLET tags that Java-capable Web browsers take advantage of when they run an associated applet.

Applets access the attributes in the <PARAM> tag by using the getParameter() method. This enables applets to look and behave differently when used in various Web documents.

The <PARAM> tag has two attributes that must be defined: the NAME attribute and the VALUE attribute. The NAME attribute assigns the name for which the getParameter() method in your applet searches. The VALUE attribute is used to pass a specific value to an applet. Here is an example using these attributes:

<HTML>
<HEAD>
<TITLE> Scrolling Text </TITLE>
</HEAD>
<BODY>
<APPLET CODE="ScrollText" WIDTH=800 HEIGHT=400>
<PARAM NAME=text VALUE= "Introducing the Java ScrollText Applet!">
<PARAM NAME=width value="800">
<PARAM NAME=height value="390">
</APPLET>
</BODY>
</HTML>

Note
Do not confuse the NAME attribute of the <PARAM> tag with that of the <APPLET> tag. The name in the <PARAM> tag is the name that the getParameter() method searches for, as opposed to the <APPLET> attribute NAME, which is used to give each instance of an applet a name.

In the previous example, the applet ScrollText is being passed three separate parameters: The first is the text the applet will display; the second and third are the width and height again. The last two parameters are included because when an applet is displayed by a Web browser, the dimensions of the applet are taken from the HTML code. This can cause problems if the creator of the applet does not prepare for it.

Parameters from Inside Java Code

All of this seems easy from the outside, but to understand how this works in the Java code is another matter. Listing 15.2 shows the code for the ScrollText applet.

In the listing, the getParameter() method is used on lines 16, 17, and 30. These are the points where the Java code brings in the <PARAM> attributes listed in the HTML document. There can be as many <PARAM> attributes given as needed for the applet. For example, the ScrollText applet could be extended to receive other attributes such as the color of the text or the background. This would be a good project to undertake after you read Chapter 16, "Applet Reuse."

Note
In Listing 15.2, code lines that use the getParameter() method are highlighted with bold text.


Listing 15.2. The ScrollText applet.
import java.awt.Graphics;
import java.awt.Font;

/**
 * Peter Norton's Guide to Programming Java
 * The Java ScrollText Applet
 * This applet is used to scroll a text banner across the screen
 * The applet takes TEXT, WIDTH, and HEIGHT as parameters.
 */

public class ScrollText extends java.applet.Applet implements Runnable {

     int h;                    // Height of applet in pixels
     int w;                    // Width of applet in pixels
     char separated[];         // Output string in array form
     String s = null;          // Input string containing display text
     String hs = null;         // Input string containing height
     String ws = null;         // Input string containing width
     Thread ScrollThread = null;     // Thread to control processing
     int speed=35;             // Length of delay in milliseconds
     boolean threadSuspended = false;
     int dist;

/* Setup width, height, and display text */
public void init() {
     ws = getParameter ("width");
    
 hs = getParameter ("height");
 
    if (ws == null){         // Read width as input
          w = 150;            // If not found use default
     } else {
            w = Integer.parseInt(ws); // Convert input string to integer
     }
     if (hs == null){         // Read height as input
          h = 50;             // If not found use default
     } else {
          h = Integer.parseInt (hs); // Convert input string to integer
     }
     resize(w,h);             // Set font based on height
     setFont(new Font("TimesRoman",Font.BOLD,h - 2));
     s = getParameter("text");// Read input text, if null use default
 
    if (s == null) {
         s = " The Java ScrollText Applet at work.";
     }

     separated =  new char [s.length()];
     s.getChars(0,s.length(),separated,0);
 }

/* Start new thread to run applet */
public void start() {
     if(ScrollThread == null)
     {
        ScrollThread = new Thread(this);
        ScrollThread.start();
     }
 }

/* End thread containing applet */
public void stop() {
     ScrollThread = null;
 }

// While applet is running pause then scroll text
public void run() {
     while (ScrollThread != null) {
     try {Thread.sleep(speed);} catch (InterruptedException e){}
     scroll();
     }
     ScrollThread = null;
 }

// Scroll text by determining new location to draw text and redrawing
synchronized void scroll () {
     dist--;               // Move string to left
     // If string has disappeared to the left, move back to right edge
     if (dist + ((s.length()+1)*(h *5 / 11)) == 0){
     dist=w;
}
     repaint();
}

// Redraw string at given location
public void paint(Graphics g) {
     g.drawChars(separated, 0, s.length(), dist,4 *h / 5);
 }

// Suspend thread when mouse is pushed, resume when pushed again
public boolean mouseDown(java.awt.Event evt, int x, int y) {
        if (threadSuspended) {
            ScrollThread.resume();
        }
        else {
            ScrollThread.suspend();
        }
        threadSuspended = !threadSuspended;
    return true;
    }
}

To gain experience in working with parameter passing, type the applet as shown and then compile it. Refer to Chapter 14, "Creating a Java Applet," for complete instructions on compiling an applet.

Possible Problems with Parameters

There is one problem with using the <PARAM> tag: Unless all possible parameters are listed and used in the HTML document, there is no way-short of viewing the Java code-to know what parameters are set. To demonstrate this, look again at the ScrollText applet's HTML markup without some of the parameters listed:

<HTML>
<HEAD>
<TITLE> Scrolling Text </TITLE>
</HEAD>
<BODY>
<APPLET CODE="ScrollText" WIDTH=800 HEIGHT=400>
<PARAM NAME=text VALUE= "Introducing the Java ScrollText Applet!">
</APPLET>
</BODY>
</HTML>

In the previous example, the applet would default to the height and width listed in the Java code. Anyone attempting to use this applet would find it confusing when the attributes he set in the <APPLET> tag were overridden. Therefore, HTML authors should list all unused parameters for an applet in comments in the HTML document. A comment can be added to an HTML document by placing it between the begin comment tag (<!-) and the end comment tag (->).

You could create comments for the ScrollText applet as follows:

<!- Java applet ScrollText takes TEXT, WIDTH, and HEIGHT as parameters. ->
<APPLET CODE="ScrollText" WIDTH=800 HEIGHT=400>
<PARAM NAME=text VALUE= "Introducing the Java ScrollText Applet!">
</APPLET>

Adding Animation to Web Documents

Java-based animation is everywhere on the Web, and it might surprise you to learn that the source of most of it is a single applet called Animator. Animator is useful for creating powerful animation sequences. But best of all, the Animator applet is included as a demo in the JDK.

Overview of the Animator Applet

As the name implies, the Animator applet can be used to create animation sequences. You will find the source code in the demo/Animator directory under your base installation directory for Java. This directory contains the following files and directories:

 Directory of C:\java\demo\Animator
IMAGES         <DIR>        02-23-96  2:32p images
ANIMAT~1 JAV        21,410  10-13-95 10:23a Animator.java
ANIMAT~1 CLA        14,873  10-13-95  1:54a Animator.class
IMAGEN~1 CLA           706  10-13-95  1:54a ImageNotFoundException.class
PARSEE~1 CLA           410  10-13-95  1:54a ParseException.class
INDEX~1  HTM         3,411  10-13-95  1:54a index.html
AUDIO          <DIR>        02-23-96  2:32p audio
EXAMPL~1 HTM           428  10-13-95  1:54a example2.html
EXAMPL~2 HTM           477  03-07-96  8:32p example3.html
EXAMPL~3 HTM           419  10-13-95  1:54a example1.html

Animator is one of the most complex demos in the Java API. As you can see from the directory listing, the source code for the applet is in a file called Animator.java. When this file is compiled, three class files are created: Animator.class, ImageNotFoundException.class, and ParseException.class.

Look at the sample HTML documents in this directory. The file index.html provides a brief overview of using the Animator applet. The example documents-example1.html, example2.html, and example3.html-contain three different demos.

The audio files used in the examples are in the audio directory:

Directory of C:\java\demo\Animator\audio
SPACEM~1 AU         48,072  10-13-95  1:54a spacemusic.au
1        AU            946  10-13-95  1:54a 1.au
2        AU          1,039  10-13-95  1:54a 2.au
3        AU            993  10-13-95  1:54a 3.au
4        AU          1,006  10-13-95  1:54a 4.au
5        AU          1,016  10-13-95  1:54a 5.au
6        AU          1,048  10-13-95  1:54a 6.au
7        AU            980  10-13-95  1:54a 7.au
8        AU          1,064  10-13-95  1:54a 8.au
9        AU            989  10-13-95  1:54a 9.au
0        AU          1,010  10-13-95  1:54a 0.au

The file spacemusic.au provides a soundtrack example. The other files are sound sequences used with corresponding images you will find in the images directory. The images directory contains two directories:

Directory of C:\java\demo\Animator\images
LOADIN~1 GIF         1,518  10-13-95  1:54a loading-msg.gif
SIMPLE~1       <DIR>        02-23-96  2:32p SimpleAnimation
DUKE           <DIR>        02-23-96  2:32p Duke

The loading-msg.gif image is used in the example3.html demonstration document and provides an example of startup image. The directories SimpleAnimation and Duke contain the images used to create the demonstration animation sequences.

Using Parameters in the Animator Applet

The Animator applet presents an interesting use of the <PARAM> tag to pass many types of values. Parameters the applet accepts include the following:

As you can see from the list of parameters and their uses, the Animator applet is quite versatile. Because most of the animation sequences you'll see on the Web use the Animator applet or a derivative of it, I highly recommend you look at the source code for this applet.

Creating a Java-Based Animation with Animator

Creating an animation with the Animator applet is easy. Just create a series of images and an HTML document, and add sound if you want to.

For your first animation, start small. If you want to create an original animation, use a series of only three or four images. You can also base your first animation on an existing one, such as the animation of JavaSoft's mascot, Duke, which is included in the demo. In this way, your first attempt at animation is sure to be a success.

Listing 15.3 shows a sample HTML document that uses the Animator applet and the Duke animation. Recall that because the CODEBASE attribute points to the Java demo directory, the compiled source code for the applet is actually obtained from this directory.


Listing 15.3. A sample document using the Animator applet.
<HTML>
<HEAD>
<TITLE> The Animator Applet </TITLE>
</HEAD>
<BODY>
<APPLET CODEBASE="file:///c:java\demo\Animator"
CODE="Animator" width=66 height=100 VSPACE=5 HSPACE=5 ALIGN=middle >
<PARAM NAME="imagesource" VALUE="file:///c:\java\demo\Animator\images\Duke">
<PARAM NAME="pause" VALUE="100">
<PARAM NAME="repeat" VALUE="true">
<PARAM NAME="endimage" VALUE="10">
</APPLET>
</BODY>
</HTML>

Note
Because the file paths in the CODEBASE and VALUE attributes reference the C drive, you may need to change the paths for use on your system. For example, if the JDK is installed on the D: drive, you would replace references to c: with d:. On a UNIX system, you would remove the references to c: entirely. You must change these references because the CODEBASE and VALUE attributes are used to point to the file's exact location on your file system.

Reducing Animation Flicker

A problem you will encounter whenever you use animation is flicker-that annoying wavering of the image or text as the applet redraws the screen. If you tested the ScrollText applet, you saw that the animated text flickered, and it probably annoyed you.

To fix the flickering of the ScrollText applet you need to draw the text first to a canvas that is off the screen. When that canvas has been drawn, it can be redisplayed on the screen in such a short period of time that no flicker is noticed. You will also need to modify the update() method so that it does not clear the screen between each drawing.

To create a canvas off the screen, you will need two containers. The first container is for the image or text you will draw to the screen. The second container is for the off-screen canvas. Here is the code you will need to add to the variable initialization section of the ScrollText applet:

Image offscreenImage;
Graphics offscreenGraphics;

Next, draw to the off-screen canvas and then move the animated text or graphics to the real canvas. To do this in the ScrollText applet, you will override the paint() method as follows:

public void paint(Graphics g) {
   Rectangle r = bounds();

   offscreenGraphics.clearRect(0,0,r.width,r.height);
   offscreenGraphics.drawChars(separated, 0, s.length(), dist, 4*h/5);
   g.drawImage(offscreenImage, 0, 0, this);
}

The final step is to override the update() method so that it does not clear the screen between each drawing. This is done as follows:

public void update(Graphics g) {
      paint(g);
}

The complete source code for the ScrollText applet with the flicker fix is shown in Listing 15.4.


Listing 15.4. The ScrollText applet with flicker fix.
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Image;
import java.awt.Rectangle;

/**
 * Peter Norton's Guide to Java Programming
 * The Java ScrollText Applet With Flicker Fix
 * This applet is used to scroll a text banner across the screen
 * The applet takes TEXT, WIDTH, and HEIGHT as parameters.
 */

public class ScrollText extends java.applet.Applet implements Runnable {

   int h;            // Height of applet in pixels
   int w;            // Width of applet in pixels
   char separated[];         // Output string in array form
   String s = null;         // Input string containing display text
   String hs = null;         // Input string containing height
   String ws = null;         // Input string containing width
   Thread killme = null;      // Thread to control processing
   int speed=35;         // Length of delay between positions in milliseconds
   boolean threadSuspended = false;
   int dist;
   Image offscreenImage;
   Graphics offscreenGraphics;

/* Setup width, height, and display text */
public void init() {
   ws = getParameter ("width");
   hs = getParameter ("height");
   if (ws == null){         /* Read width as input, if not found use default */
      w = 150;
   } else {
        w = Integer.parseInt(ws); // Convert input string to integer
   }
   if (hs == null){         /* Read height as input, if not found use default */
      h = 50;
   } else {
      h = Integer.parseInt (hs); // Convert input string to integer
   }
   resize(w,h);         /* Set font based on height */
   s = getParameter("text");   /* Read input text, if null use default */
   if (s == null) {
       s = " The Java ScrollText Applet at work.";
   }

   separated =  new char [s.length()];
   s.getChars(0,s.length(),separated,0);
   offscreenImage = createImage(w,h);
      offscreenGraphics = offscreenImage.getGraphics();
   offscreenGraphics.setFont(new Font("TimesRoman",Font.BOLD,h - 2));
 }

/* Start new thread to run applet */
public void start() {
   if(killme == null)
   {
        killme = new Thread(this);
        killme.start();
   }
 }

/* End thread containing applet */
public void stop() {
   killme = null;
 }

/* While applet is running pause then scroll text */
public void run() {
   while (killme != null) {
   try {Thread.sleep(speed);} catch (InterruptedException e){}
   scroll();
   }
   killme = null;
 }

/* Scroll text by determining new location to draw text and redrawing */
synchronized void scroll () {
   dist-;         // Move string to left
   if (dist + ((s.length()+1)*(h *5 / 11)) == 0){   // If string has disappeared
                           //to the left, move back
   dist=w;                     //to right edge
      }
   repaint();
}

/* Redraw string at given location */
public void paint(Graphics g) {
   Rectangle r = bounds();

   offscreenGraphics.clearRect(0,0,r.width,r.height);
   offscreenGraphics.drawChars(separated, 0, s.length(), dist, 4*h/5);
   g.drawImage(offscreenImage, 0, 0, this);
 }
public void update(Graphics g) {
      paint(g);
}

/* Suspend thread when mouse is pushed, resume when pushed again */
public boolean mouseDown(java.awt.Event evt, int x, int y) {
        if (threadSuspended) {
            killme.resume();
        }
        else {
            killme.suspend();
        }
        threadSuspended = !threadSuspended;
    return true;
    }
}

Publishing a Java Presentation on the Web

Now that you are familiar with the Java extensions to HTML, you can put together your first Java-powered Web presentation and publish it on the Web. But before you begin, there are some things you should consider as to when and where to use applets.

Using Live Applets

Determining when and where applets should be used in Web pages is not always easy. Prior to making the decision to fill your Web pages with applets, ask yourself if they are truly useful and if they enhance the page. If they do not, and only add to the load time of the page, perhaps it would be better not to use them. Sure, it's great to show off and display a visually exciting page, but consider how often someone will return to your page if it takes 10 minutes to load into the Web browser.

Journalists always talk about the five Ws. It should be no different in electronic publishing, except that instead of applying them to a story they are applied to the construction of a Web presentation.

The first W is Who-in this case, your target audience. There has been much ado in the press about the short attention span of today's youth, especially that segment often referred to as Generation X. If this is your target audience, what are the odds of them waiting through an extremely long page load when other places are just a click away? On the other hand, an extremely exciting visual display can be worth the wait. There is a trade-off.

The content of your page, the What, comes next. Think about what you are displaying. If it is a fan page that could be enhanced by the visual display of animation or use of sound, using Java applets left and right may be appropriate. If you are trying to sell something, scrolling messages will attract the eye. Perhaps using Java applets to demonstrate a sample of a software product would help sell more copies. Whatever the case, a few Java applets will more than likely make it all the more appealing, but overuse can kill the best of things.

The third W, When, is easy. Start using Java applets as soon as you are comfortable with your ability to create and incorporate a useful applet into your presentations. Java is experiencing tremendous growth right now. Internet users continually expect more interaction with the sites they visit. They expect sites to employ new technology as soon as it is available, and they are waiting to visit more Java-powered Web sites.

Where do you place the applets? Where they will achieve the effect you desire. If the applet is central to the design of the page, place it centrally on the page. Placing a small animation at the bottom of a page is usually a bad idea. If the applet is on the page just to serve as notification that you can use applets, then consider not using it at all. Remember that what is at the topmost center of a Web presentation will be the first thing users see. Do your best to use this space to grab their attention, because other Web presentations are always just a click of a mouse button away.

The last W, Why, is the hard part. I have pointed out several good reasons both for and against using Java applets. The best incentive I can think of for using Java applets is their capability to draw people in. A well-written applet will be noticed. Friends will tell friends about it, and some people will visit your Web presentation just to view the applet. However, a set of "been there, done that" applets will likewise keep people away unless your Web presentation provides something of value to them. A good rule of thumb is to use an applet if it provides additional value to your presentation.

The use of Java applets in and of itself will not guarantee a successful Web presentation. Using Java applets to enhance a good presentation will only make it better. Successful presentations come from organization, planning, and hard work. Plan your site before you develop and publish it. If an applet is not part of the original plan, design the modification to your site as carefully as you would plan a change to your software. This will save you a lot of time trying to fix the site later.

Putting Together the Presentation

After you consider when and where to use applets in your Web pages, you can start putting together your presentations. Your first Java-powered Web presentation incorporates everything I have discussed to this point in the chapter. Along with the RGB2Hex converter and the ScrollText applet, the presentation includes an animation featuring Duke that comes to life with the Animator applet. As you look over the markup in Listing 15.5, pay special attention to the CODEBASE locations.

Using CODEBASE, it is not necessary to physically locate the applets in the same directory as the HTML document. In fact, in this example, all the applets are in separate locations: RGB2Hex is in rgbconvert under the base directory; ScrollText is in scrolltext under the base directory; and Animator is in the animator directory.


Listing 15.5. A Java-powered Web presentation.
<HTML>
<HEAD>
<TITLE> Java-powered Web presentation </TITLE>
</HEAD>
<BODY>
<CENTER>
<H2> The RGB to Hex Converter </H2>
<HR>
<P>
<APPLET CODEBASE="rgbconvert" CODE="RGB2Hex" WIDTH=300 HEIGHT=300 >
<IMG SRC="RGB2Hex.gif">
<BLOCKQUOTE>
The screenshot shows the RGB2Hex applet programmed in the Java
programming language. This applet lets you convert RGB color
values to hexadecimal values and see the corresponding color output.
Other applets on the page display scrolling text and an animated image.
To see all this, you should get a Java-capable Web browser
such as the Netscape Navigator 2.0.
</BLOCKQUOTE>
</APPLET>
<HR>
<!- Java applet ScrollText takes TEXT, WIDTH, and HEIGHT as parameters. ->
<APPLET CODEBASE="scrolltext" CODE="ScrollText" WIDTH=800 HEIGHT=50>
<PARAM NAME=text VALUE=" The Java ScrollText Applet at work. ">
<PARAM NAME=width VALUE="800">
<PARAM NAME=height VALUE="50">
</APPLET>
<HR>
</CENTER>
</P>
<P ALIGN=right>
<STRONG>Powered by JAVA</STRONG>
<APPLET CODEBASE="animator"
CODE="Animator" width=66 height=100 VSPACE=5 HSPACE=5 ALIGN=middle >
<PARAM NAME="imagesource" value="images/Duke">
<PARAM NAME="pause" VALUE="100">
<PARAM NAME="repeat" VALUE="true">
<PARAM NAME="endimage" VALUE="10">
</APPLET>
</P>
</BODY>
</HTML>

Note
This example assumes that you've published all the necessary files for the presentation as outlined in the next section of this chapter. If you want to use the presentation on your local system, you will need to check and possibly update the file paths to the applets and image files.

The Web presentation is almost finished; but before we publish it, there are a few more things you should add. The first thing relates to the Duke animation. The caption above it says "Powered by Java", and, as unlikely as it may seem, there may be a few people browsing the Web who have not heard of Java. So, why not provide a link to the Java home page?

The best place to provide a link to the Java home page is on the word JAVA. The HTML code to provide this link uses the anchor tag (<A>) and is simple to add. The modified line in our Web document now looks like this:

<STRONG>Powered by <A HREF="http://java.sun.com">JAVA</A></STRONG>

Now the word JAVA will show up as a highlighted link to the JavaSoft home page. But if we can do that, why not modify the code like this:

<A HREF="http://java.sun.com">
<APPLET CODEBASE="animator"
CODE="Animator" width=66 height=100 VSPACE=5 HSPACE=5 ALIGN=middle >
<PARAM NAME="imagesource" value="images">
<PARAM NAME="pause" VALUE="100">
<PARAM NAME="repeat" VALUE="true">
<PARAM NAME="endimage" VALUE="10">
</APPLET>
</A>

After all, why not just make the applet itself the link to the home page? You cannot do this because it does not have the expected result of linking to the Java home page when the user clicks the applet. The applet traps the mouse-click event itself as opposed to allowing the HTML code to handle it. So, although applets may contain links or provide links, they cannot themselves be links.

The last thing I recommend adding to a Web presentation is another <A> tag, but this time it should include a mailto reference. This reference tells the reader's browser to open a create mail session that will be sent to the named user and provides a method for getting feedback on your Web presentation. The following mailto reference lets the reader send mail to the address for reporting bugs and making feature requests for Java:

<A HREF="mailto:java@java.sun.com">java@java.sun.com</A>

The finished presentation is shown in Figure 15.2. This sample presentation is quite basic,

Figure 15.2 : The finished presentation.

but it should help you envision how wonderful Java-powered presentations can be.

After all this, the Web publication looks pretty good. You have defined APPLET elements with their associated attributes and have incorporated them into an HTML document. The next step is to publish the presentation as a page on the World Wide Web. The page can be created to be viewed alone or as part of a group of related pages. Regardless of the number of pages, a display of information on the Web is considered a Web publication.

Publishing the Presentation on the Web

To publish your Java-powered presentation, you need access to a Web server through an Internet service provider, a commercial service provider, or another entity. Now you are ready to publish your presentation.

Step 1: Determine Where to Place Your Documents

The first step in publishing a Web document is to decide where it and all its supporting material will be stored. On many of the servers connected to the Internet, all materials set for publication on the Web must be stored in a specific subdirectory in the user's home directory. This subdirectory typically is named public_html on UNIX-based Web servers, but the best way to determine the directory for your HTML documents is to ask the Web server administrator.

Note
Always turn to the server administrator if you have questions about directories or storage. The server administrator should understand the proper structure of the system you will be working with and can help prevent many mistakes.

Usually, Web servers map URL paths to the public_html subdirectory, and you can point to it using the tilde (~) followed by your system name. Thus, requests to http://www.your_provider.com/~you would be mapped to the subdirectory called public_html in your account, and a Web document called present.html could be accessed with the following URL:

http://www.your_provider.com/~you/present.html

Step 2: Create the Necessary Directory Structure

You should prepare your home directory for Web publishing by creating the appropriately named Web directory and any necessary subdirectories. From the command prompt in your home directory on a UNIX or Windows-based server, you can create a directory called public_html by typing the following command:

mkdir public_html

Make sure that the directory has the appropriately restricted mode for Web access, such as 705 on a UNIX system. The mode 705 means that the directory is readable, writeable, and executable by you, but only readable and executable by others. To change the mode of the public_html directory, type the following command:

chmod 705 public_html

Afterward, change to the public_html directory and create subdirectories as necessary. The use of subdirectories helps to keep everything clear and organized inside the public_html directory. As mentioned earlier, using CODEBASE frees you from having to keep the .html files with the .java or .class files. Create subdirectories for the ScrollText, RGB2Hex, and Animator applets by typing the following:

cd public_html
mkdir rgbconvert
mkdir scrolltext
mkdir animator
cd animator
mkdir images

Note
Be sure the CODEBASE attribute for the RGB2Hex applet points to the subdirectory rgbconvert. Similarly, the CODEBASE attribute for the ScrollText applet should point to the subdirectory scrolltext.

Step 3: Move Your Documents

Next, use FTP or whatever protocol you are comfortable with to upload all files necessary for the presentation to the appropriate directories. The RGB2Hex.java, ScrollText.java, and Animator.java files are not necessary to run the Java applets. Therefore, they are not uploaded.

Upload the following files to the rgbconvert directory: RGB2Hex.class, RGBcanvas.class, RGBcontrols.class, and HexInt.class. Upload ScrollText.class to the scrolltext directory.

If you installed the JDK, you can find the Animator applet in the Java demo directory on your computer. Under this directory are subdirectories for the images. You will find the images for the Duke animation in the images/Duke directory. Upload the following files to the animator directory: Animator.class, ImageNotFoundException.class, and ParseException.class.

Now upload the following files to the animator/images directory: T1.gif, T2.gif, T3.gif, T4.gif, T5.gif, T6.gif, T7.gif, T8.gif, T9.gif, and T10.gif.

Next, save the HTML document for the presentation as present.html and upload it to the public_html directory. Some computer systems do not allow for file extensions beyond three characters. If this is the case on your system, save the document as present.htm and change the filename when it is on the Web server.

After uploading the files, ensure that the correct permissions are set on the files. File modes are similar to directory modes. On UNIX systems, the mode 705 is generally the appropriate access mode for your files. On other systems, you will want to ensure that the files are readable but not writeable.

Note
If you are interested in publishing on the Web, I highly recommend Web Publishing Unleashed, published by Sams.net. The book goes into great detail on every aspect of Web publishing and includes chapters on HTML, SGML, VRML, and much more. In particular, you may want to refer to Chapter 25, "Designing and Publishing a Web Document," which provides a complete walk-through of publishing a Web document, and Chapter 26, "Designing and Publishing a Web Site," which provides a complete walk-through of publishing a Web site.

Viewing the Presentation

To view your Java-powered presentation, you'll need to use a Java-enabled Web browser. These will automatically run any applets on a page when that page is first accessed. If you don't have a Java-enabled browser, refer to Chapter 3 to learn how to obtain and install a browser for your system.

As of this writing, browsers capable of running Java 1.0 applets include the following:

When you have a Java-enabled browser, you can view your Web presentation. To do this, point your browser at the appropriate URL, such as the following:

http://www.yourprovider.com/~yourid/present.html

After downloading the document called present.html, your browser will download the necessary files to run the applets in the presentation. Therefore, you will notice a slight delay before the applets display. Now, all that's left is to wait for some feedback on your presentation.

How Does Java Compare to Other Available Products?

Java is a wonderful language and, for what it was designed to do, no other language comes close to it. However, this does not mean that it is a cure-all that does everything. Java as a programming language can be compared with other general-purpose programming languages, including the advantages of the different languages and the different ways they are used on the World Wide Web. The following sections perform this comparison. Although HTML is not considered a programming language, the boundaries between Java and HTML are also explored here.

Java Versus Perl

Perl has long been the preferred language of CGI programming. For server-based programs, few languages offer the power combined with ease of programmability to match Perl. Perl's true strength lies in its capability to perform rapid text parsing and its excellent string-manipulation features. When strictly dealing with text, Perl is often much faster than Java. However, Perl does not have Java's strong graphics capabilities.

Java is a distributed language, which means that it does not have to run on the server as Perl generally does. In addition to saving processing power on the server, Java applets can be moved from site to site more easily. Having Java run on the client means that Java can be stored on and run off any type of server without any change to the source or class files. Perl files can be moved from site to site, but they often require slight modifications after the move.

The biggest limitation of Java applets compared with Perl is that Java cannot write information to the server. However, this is a security issue, not a lack of programming power on Java's part. Look for problems such as this to be addressed within the next year.

Java Versus Other Programming Languages

Java can be compared with other languages besides Perl. Scripts can be written in the UNIX shell, C, or C++, which have the advantages of being well known and popular. They provide many low-level routines that Java does not supply. They enable the programmer to customize the application for a particular operating system or hardware. They also have been in use for many years, so there is a large quantity of existing routines for each. Therefore, don't expect Java to replace them in every area.

Java is a robust and powerful distributed language. Java's security also far surpasses the other languages discussed. However, this security is not needed in all applications. Java supports code reuse, but if large portions of the code already exist in another language, that may be the most appropriate language to use. Java's system independence is an advantage, but there is still an associated overhead. For areas that require a lot of numeric calculations, C may provide much faster response time. (See Chapter 18, "Using Java Applications in the Real World," for the inside scoop on using C and C++ routines with Java.)

Often, discussions about programming involve drawing analogies to carpentry or mechanics. These analogies are correct in stating that a programmer, like a carpenter, should use the right tool for the job at hand. A new nail gun will never be a reason to replace a trusty hammer, and a hot new programming language is no reason to abandon one with which you are comfortable.

Use the programming language that is appropriate for the job. If your project requires writing to a server, perhaps Perl or C++ would be your best choice. But for creating distributed applets or applications to run on the Internet, Java has no rival. Let the job dictate the proper tool. This is true for distributed software as well as for custom applications.

Java Versus Off-the-Shelf Software

Will distributed programs written in Java replace much of the off-the-shelf software of today? Although this might sound like a good selling point for Java, several technological advances will be required before this comes to fruition. Security and connection speeds, for example, must continue to improve.

Although Java is more secure than most general-purpose software-development languages, this security is not yet generally accepted. As the language becomes more widely used, there will be an increase in attempts to breach the security. Security will probably improve as the language develops, however, and the wider use of Java will help eliminate these concerns for many people.

Many of the speed concerns regarding transfer time for Java applets will be eliminated if ISDN or cable modems become the next standard for Internet connections. Using ISDN, you can connect at 64Kbps, 128Kbps, or more. Using cable modems, you can connect at speeds exceeding one megabit per second. However, to expect transfer rates for data across the Internet to approach the transfer rates of typical hard drives sounds a bit far-fetched at this time. Until these problems can be addressed, software manufacturers can remain confident that users will want to purchase and install local copies of most of their software.

Can Java produce software comparable in quality to what is seen on retailer's shelves? Yes. As an application-programming language, Java is quite competitive. In the upcoming chapters you will see how Java can be used for creating stand-alone programs as well as how it can support development by combining with other languages to produce robust programs. To complete this section, let's look at how Java works with HTML to meet user needs over the Internet.

Java Versus HTML

For several years, HTML has been the de facto language of the World Wide Web. Expecting Java to replace it is out of the question; all Web browsers make use of the markup tags inside HTML to display a Web publication. Java is an extension of this capability, not a replacement for it.

Some programmers believe that Java may assist in replacing the ever-expanding set of HTML tags. Instead of relying on HTML to format a Web document, they believe that Java can handle the formatting. However, because Java applets take significantly longer to transfer and run, I doubt that this will be put to use in the near future. For most sites, users would prefer to get rapid access to information. Because HTML files are transferred as plain text, they can be downloaded in very little time.

When HTML documents include images and sound clips, the transfer time is increased. In this case, Java might not significantly increase the time to load the page. However, if the images are static and can be successfully displayed using HTML tags, there might not be any reason to use Java. When the images would be more interesting if viewed one at a time, it might be advantageous to create an applet to display them. If the user would benefit by being able to start and stop the sound clip, a Java applet could enhance the page as well.

Java is best working with HTML, not trying to replace it. Java provides more capability for user interaction, but requires more patience on the part of the users. Java is an extension to HTML similar to the CGI scripts that first allowed users to enter data in response to HTML forms. Applets that allow storage of multiple URLs are actually a replacement of the CGI programs that do the same thing. Both CGI and Java still rely on HTML for display and distribution across the World Wide Web.

The future may well see faster data-transfer speeds across the Internet and thus make the viewing of multiple applets a less time-consuming event. If this happens, expect to see even more applets than are in use today, perhaps even Web presentations that are in fact an applet in and of themselves. In the meantime and for the foreseeable future, Java and HTML are partners.

Summary

In this chapter, the discussion has moved from placing Java applets on the World Wide Web to HTML tags to selecting the proper language for programming. Some of this might seem confusing until you have the experience of putting it into practice. When you begin to move applets from your computer to a server for display on the Internet, however, most of it will become clear. Just as with programming, the best way to learn is to practice.

The Internet is changing daily, but most of the change is merely growth and extension of protocols and methods that were already in place. What you have learned in this chapter is not final; it is only a jumping-off point into the Internet. Expect Java to continue to grow and expand alongside the Internet and, most of all, just have some fun with it as you go along.