Previous Page TOC Next Page



31


Including Java Applets in Your Web Page


by Rick Darnell and William Robert Stanek

Introduction


Java is one of the hottest topics on the World Wide Web and for good reason. It offers expanded portability for Web content, including sound and animation, without the use of plug-ins or other helper applications and independent of host hardware. In this sense, Java has helped promote a change in the way page developers think about content on the World Wide Web, similar to the way the World Wide Web changed the way people think about the Internet.

Getting to Know Java


Java is an object-oriented programming language developed by Sun Microsystems, Inc. Although not initially conceived as a way to expand the interactivity and capability of Web pages, it didn't take long for people to see how the platform-independent nature of Java made an ideal fit with the nature of the Internet.

In the past, when an author developed a page with special content beyond the constraints of HTML, he had to make an important decision: either use helper applications or shift the necessary processing to the server. The first solution meant that some content was inaccessible to some users if they didn't have the helper application or if a helper was unavailable for their system. The second solution meant excluding some content because inherently slow modem lines made animation and sounds unworkable over normal network connections.

Enter Sun's Java. By utilizing a key feature of Java—platform independence—Java applets can implement sound, animation, spreadsheets, e-mail applications, guest books, and virtually anything else you can program, regardless of platform.

Java Safety


Running in a distributed environment, such as an intranet or the World Wide Web, requires safeguards for client computers; a potentially hostile piece of code can do a great deal of damage by erasing files, formatting disks, and creating other types of damage. Given the way applets are implemented—automatic load and run—you need to ensure the integrity of any piece of code distributed to a broad and uncontrolled audience.

As a Web page author using Java, you have the responsibility to ensure that your applets are clean. The best way is to get them only from trusted sites. Be careful about picking up applets anywhere you find them—the hard drive you save may be your own.


Programmers Love a Challenge

Java is not bulletproof. As quick as it was proclaimed secure, a dedicated group of programmers went to work to find security holes, and they found them. Through cooperative efforts between Sun, Netscape, Microsoft, and others, most of these security problems were taken care of, but it's still a dangerous world.

You can do a few things to protect yourself and your system.

  • Only use the most up-to-date versions of software. This includes using the most recent version of Java for your coding efforts. Java version 1.02 fixes most security problems found in Java version 1.0. Java version 1.1 will introduce even tighter security controls.
  • If your system allows screening applets at the firewall, take advantage of it. If there are applets you'd like to use, make them available internally.

As discussed in the introduction, the compiled bytecode is checked extensively for illegal operations and verified again on the host system before the applet is run. Although these security features limit the scope and capabilities of an applet, they also help ensure against Trojan horse viruses and other shenanigans by less-than-scrupulous programmers.

With all the security features built in, you don't want to implement word processors, spreadsheets, or other interactive applications within the context of a browser. If you require these programs, consider building a full Java application, which does not contain the security restrictions of an applet.


Although no system can guarantee 100 percent security, Java goes a long way to ensure the protection of client systems from its applets. It uses three security procedures to make the end user safe from malicious attacks:


Bytecode Verification

After a piece of Java code is loaded into memory, it enters the interpreter, where it is checked for language compliance before the first statement is executed. This process ensures against corruption or changes to the compiled code between compile time and runtime.

Memory Layout

Next, the memory layout is determined for each of the classes, preventing would-be hackers from forging access by deducing anything about the structure of a class or the machine it's running on. Memory allocation is different for each class, depending on its structure and the host machine.

File Access Restrictions

After that, the interpreter security continues to monitor the activity of the applet to make sure it doesn't access the host file system, except as specifically allowed by the client or user. You can extend some implementations of this specific feature to include no file access at all.

Platform Independence


The platform-independence feature is probably the most important one. One compiled piece of Java code can run on any platform with a Java compiler. Currently, the list of platforms includes Windows 95, Solaris, and Macintosh, but people are hard at work to expand the possibilities. By its very nature, Java does not contain any implementation-specific syntax. This format means a byte is an 8-bit integer and a float is a 32-bit IEEE 754 floating-point number, no matter where the applet runs.

With object-oriented code, Java takes advantage of a special programming feature that allows programmers to upgrade capabilities by simply adding a new class. When an applet is upgraded, it is not always necessary to reload the entire applet. A small additional class may be all that's needed.

HotJava


HotJava represents one of the first applications written entirely in Java (see Figure 31.1). In its initial release, HotJava primarily showed how applets could be included as part of an HTML document. Now, it functions similarly to a full-featured browser.

Figure 31.1. The HotJava browser is one of the first stand-alone applications written entirely in the Java language.


TIP

To download a copy of HotJava, point your browser to http://java.sun.com/java.sun.com/hotjava.html. The file size is approximately 3MB.


HotJava operates differently from most browsers in its basic functioning. Settings, preferences, and other basic maintenance screens get stored in the form of HTML documents and classes.

Stripped down to its most basic level, HotJava knows nothing about anything. Classes are added to the browser so it can understand HTML, e-mail, sound files, and other specialty items. As new content and new formats are developed for Web pages, Java only requires the addition of another class. You won't need a complete upgrade to a new version to take advantage of the latest developments.

The Truth About Java-Powered Pages


When Java was first released in 1995, if you wanted to do something nifty on your Web page with an applet, you needed two things:

Fortunately, this situation didn't last very long. Thousands of programmers and Web developers became interested in Java and before long, applets were available everywhere. Second, Netscape adopted Java compatibility for its 2.0 release of Navigator. This decision was followed closely by Microsoft, who included Java support as part of its 3.0 release of Internet Explorer.


TIP

If you're still interested in writing your own applets, the basics are covered in Chapter 32, "Writing Java Applets." For a detailed programming tutorial, check out Peter Norton's Guide to Java Programming, available from Sams.net.


HotJava is available but remains a distant choice in the browser market. Although easily customized using Java classes, it's still pretty slow. Sun is not attempting to compete with the Big Two and instead focuses on intranet and custom markets.

With plenty of applets and Java-compatible browsers, making a Java-powered page is as simple as including an applet definition within your HTML document. To wave the Java banner, many page authors also include the Java-powered icon (see Figure 31.2) as part of the page with the applet or links to other Java pages.

Figure 31.2. The Java-powered icon is used by many developers to indicate a page with Java applets.

Why Is Everyone so Hyped About Java?


Java holds a great deal of promise for the World Wide Web and computers in general because it provides a solution to the problem of incompatible platforms. The Internet and intranets are no longer expected to include similar or directly compatible machines (all UNIX, all Macintosh, or all PC). Because it has a neutral architecture, the same application written in Java can be used by anyone on the network, without concern for what kind of machine the developer used.

For stand-alone applications, Java's object-oriented structure provides an easy method to upgrade. The class for the upgrade or extension of the application is downloaded into the appropriate class library; then, you can run the updated features.

With its modeling capabilities, Java represents a good choice for implementing advanced Web capabilities and content, such as virtual reality sites or Web crawlers powered by intelligent agents.

How to Use Java Now


The simplest way to implement Java is through embedding applets in your HTML pages. A wide variety of applets are already available for inclusion, including the animation applet included with the Java Development Kit and a plethora of "ticker" display applets.

How Applets and Applications Are Different


Java applications work similarly to stand-alone programs, such as your browser or word processor. They don't require a third-party intermediary, such as HotJava or the AppletViewer. Applets require a Java-compatible browser or the AppletViewer for viewing. They operate similarly to other objects embedded in HTML documents, such as Shockwave or RealAudio files, which require assistance to run.

Because applets run on a host system, they are especially suspect and lead to several key security restrictions. Applets have limited capability to interact with their host platform. An applet cannot write files or send files to a printer on the local system. In addition, it cannot read local files or run local applications. Although no system is 100 percent secure, Java goes to great lengths to ensure the integrity of applets generated under its banner.


Java Applets and JavaScript

It has been said a million times, but if you have just started using Java, it bears repeating. Java isn't JavaScript. JavaScript isn't Java.

Java, in applet or application form, is a compiled language with classes and inheritance. HTML pages can include a reference to Java applets, which then get downloaded and run when a compatible browser finds the tag.

JavaScript is an object-based, client-side scripting language developed by Netscape, but it does not include classes or inheritance. JavaScript exists on the HTML page and gets interpreted by a compatible browser along with the rest of the page.

Although they share some common syntax and terminology, the two items work differently and have different uses. Confusing Java and JavaScript only leads to a steeper learning curve.



Using an Applet on a Web Page


Using applets on a Web page requires a two-part process. First, you must make sure your classes and related files, such as images and audio clips, appear in a directory accessible to the HTML page. One common location is in a classes subdirectory of the HTML documents.

Second, the applet tag that refers to the class is inserted in the Web page, along with any parameters the applet needs to function.


NOTE

If your browser is not Java-compatible, the applet section of the HTML page is ignored.



Setting Applet Properties

To add an applet to your page, start by clicking the Advanced toolbar's Insert Java Applet button. This opens the Java Applet Properties dialog box shown in Figure 31.3.

Figure 31.3. Setting applet properties.

Although it looks like you have a lot of options, they're actually pretty simple to understand. The Applet Source field provides your browser with the filename for the compiled applet, such as myApp.class. The Applet Source field 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, you must fill in the Applet Base URL field to indicate the path to the applet, such as www.yourserver.com/docs/.

A key field you should fill in is the Message for Browsers Without Java Support field. Browsers that don't support Java display whatever you place in this field. As you see in Figure 31.3, this field can contain text and markup.

Telling your browser where to find the applet usually isn't enough. Most applets also require a set of parameters to control its actions. Without parameters, applets could not communicate with each other, and you could not pass general-purpose values to applets. You'll learn more about parameters in the next section.

You can work with applets like any other type of object on the page. To adjust the size of the applet, you use the Height and Width properties of the Size field. Using the properties of the Layout field, you can precisely place your applet on the page. The Alignment property lets you specify how the applet is aligned with text on the same line or area of the page. In the drop-down list for the Alignment property, you see nine alignment values, which are the same alignment values used with images.

The spacing around your applet is also important. You specify the amount of horizontal and vertical space in pixels. Horizontal spacing is the area above and below your applet. Vertical spacing is the area to the left and right of the applet.

When you add an applet to a page, the FrontPage Editor inserts a large icon that says Java in bold letters. You can double-click this icon to open the Java Applet Properties dialog box. Click once on the icon to manipulate the size and position of the applet. On both ends and in the middle of a selected applet are resizing points. If you move the pointer to a resizing point and click and hold the left mouse button, you can add vertical and horizontal spacing by dragging the pointer. If you move the pointer to a different area of the applet icon and click and hold the left mouse button, you can drag the applet to a new location on the page.

Passing Parameters to Applets

Parameters pass information to applets about its environment and how it should behave in the current HTML document. Some applets have one method of running and don't accept any parameters. Most, however, contain some user-definable parameters that can be changed.

Check any documentation supplied with the applet to see what's available. There is no limit to the number of parameters you can include within an applet tag.

You use the Applet Parameters area of the Java Applet Properties window to work with parameters. Parameters are set in name/value pairs like most extensions. You click the Add button to add new parameters. You click the Modify button to modify the currently selected parameter. You use the Remove button to delete the currently selected parameter.

To add a parameter to an applet, click the Add button, which opens the dialog box shown in Figure 31.4. In the Name field, enter the name of the parameter you are setting. In the Value field, set the parameter to a specific value.

Figure 31.4. Setting applet parameters.

Parameter names are case sensitive and must exactly match the parameter names in the applet. If the applet does not provide exceptions for mismatched data types, an incompatible value could cause the applet not to function. For example, if a parameter looks for an integer and you enter a text string, the applet could fail to operate.

There is a small complexity to all of this. You'll notice that FrontPage defines all parameters within quotation marks, meaning all parameters are passed as strings. What gives?

The nuance is that parameters are always sent to applets as strings, regardless of how you represent them in the parameter tag. The conversion to the appropriate data type happens inside the applet. The moral to this story is to make sure the value you send will convert to the right type.

More on Messages for Browsers Without Java Support

While interpreting an HTML document, an incompatible browser ignores any tags it doesn't understand. In this case, that includes the applet and its parameters. However, the browser ignores them one at a time instead of finding the closing applet tag and ignoring everything in between. When the browser reaches elements you've defined in the Message for Browsers Without Java Support field, the browser knows what to do and handles any additional elements perfectly (see Figure 31.5).

Figure 31.5. Even though NCSA Mosaic is not compatible with Java, it can display a graphic in place of the applet.


TIP

Make sure the actual size of your image matches the dimensions of the applet. If the size defined in the image tag is different from the actual size, it could be distorted on the viewer's screen.


This is an easy way to substitute content for users who don't have Java-compatible browsers. Although all the benefits of Java are lost, at least the users have something to view, even if it's a message saying that they should get a Java-capable browser.

Applets for Fun and Utility


This section provides help on using a selection of applets available on the CD-ROM. These applets are free for you to use on your own Web pages.

This section provides help on using a selection of applets available on the CD-ROM. These applets are free for you to use on your own Web pages.

Animator


Probably one of the most frequently used, the Java animator applet shown in Figure 31.6 comes with the Java Development Kit and provides a quick-and-easy way to add animation to your Java-powered page.

Figure 31.6. The Animator applet displays a series of images with an option for frame-specific sounds and soundtracks.

Animator also supports synchronized sound with the animation, but the sound must use the Sun AU format. No other sound formats are supported yet.

Implementing the applet requires a set of GIF or JPG files containing the images that form the animation. Try to keep the size of the images as small as possible. Each image must be downloaded to the client machine, adding significantly to the time required for the applet to load and run.

To use the Animator applet, here is how you should set the properties in the Java Applet Properties window:

  1. Set the Applet Source field to Animator.class.
  2. Width should be at least the width in pixels of the widest frame, whereas height should reflect the size of the tallest frame. Smaller values result in the image getting clipped.
  3. If the Animator's class files are not in the same directory as the HTML document that uses the applet, you must set the Applet Base URL property.

Next, you need to set parameters for the applet. These parameters control the operation of Animator. You add parameters by clicking the Add button. Table 31.1 shows the parameters names and the appropriate values for the parameters.

Table 31.1. Parameters for the Animator applet.

Name Value Description of Value
BACKGROUND filename An image file for use as a background for the animation. Example: wallpaper.gif.
BACKGROUNDCOLOR color,color,color The color for the animation background, represented as an RGB value with a number from 0 to 255 for each of the settings. Example: 0,0,0.
ENDIMAGE number The last frame in the animation. Example: 10.
HREF URL The URL of the page to visit when user clicks the animation (if not set, a mouse click pauses or resumes the animation). Example: http://www.mcp.com/.
IMAGES number|number|... Used to define an explicit order for frames, which becomes useful if your frames are out of order or you want to reverse the sequence. Example: 1|2|3|2|1.
IMAGESOURCE pathInfo Points to the directory that contains the animation frames. The default directory is the same as the HTML document. By default, the files get named T1.gif, T2.gif, and so on. Example: http://tvp.com/java/apps/images.
NAMEPATTERN dir/prefix%N.suffix A pattern to use for generating names based on STARTIMAGE, ENDIMAGE, or IMAGES. Example: F%N.gif.
PAUSE number Number of milliseconds to pause between images default—can be overridden by PAUSES. Example: 100.
PAUSES number|number|... Millisecond delay per frame, with each value separated by a vertical bar. A blank value uses a default PAUSE value. Example: 100|50||100|||100.
POSITIONS x@y|x@y... Screen positions (x@y) for each frame, represented in pixels and separated by vertical bars. A blank value uses the previous frame's position. Example: 10@50|10@60|10@70.
REPEAT true If true, the animation continues as a loop. Example: true.
SOUNDS aFile.au|||||bFile.au Plays audio files keyed to individual frames. Example: s1.au|s2.au|s3.au|s4.au.
SOUNDSOURCE directory Indicates the directory with the audio files. The default is the same directory as the class. Example: http://tvp.com/java/apps/sounds.
SOUNDTRACK file An audio file to play throughout the animation as background music. Example: soundtrack.au.
STARTIMAGE number The first frame in the animation, by default 1. Example: 2.
STARTUP filename An image that gets displayed while the applet loads and prepares to run. Example: startup.gif.

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

If you want to get up and running with Animator with limited fuss, follow these steps:

  1. Create a new page in the FrontPage Editor or open an existing page.
  2. Finish the page with other HTML elements.
  3. Create a series of GIF or JPEG images for your animation. Following the default naming pattern, name your first image T1.gif, your second T2.gif, and so on.
  4. Copy the Animator class files to the same directory as the HTML document. The three class files are Animator.class, ImageNotFoundException.class, and ParseException.class.
  5. Copy the image files to the same directory as the HTML document.
  6. Move the insertion point to where you want to add the Animator applet. Open the Java Applet Properties window and then follow these steps:
      A. Set the Applet Source field to Animator.class.
      B. Set the width to the width in pixels of the widest frame.
      C. Set the height to the pixel height of the tallest frame.
  7. Add a parameter. Set the name of the parameter to endimage. Set the value to the number of the last frame in the animation.
  8. If you want the animation to repeat—and you probably do—add a parameter. Set the name of the parameter to repeat. Set the value to true.
  9. Close all open dialog boxes and save the page.

Clock


The Clock applet displays an analog clock on-screen (see Figure 31.7), complete with a sweeping second hand. Right now, no way exists to control the appearance of the clock. It would, however, be a relatively simple matter to add a parameter to control the size of the clock, whether the second hand appears, and the display of the date and time underneath.

Figure 31.7. The Clock applet, a small and simple local-time clock to include on a Web page.

The time is determined by the host machine. It occupies little computer space for a computer implementation of an analog clock—just more than 3KB. To use this applet in a Web page, follow these steps:

  1. Move the insertion point to where you want to add the Animator applet. Open the Java Applet Properties window.
  2. Set the Applet Source field to Clock2.class.
  3. Set the width to 170.
  4. Set the height to 150.
  5. Add a parameter. Set the name of the parameter to endimage. Set the value to the number of the last frame in the animation.

Nervous Text


Nervous text (see Figure 31.8) works like combining the basic HTML heading with a strong dose of really strong coffee and a slab of double-chocolate cake. The letters jitter and jump around like Mexican jumping beans on a hot pan.

Figure 31.8. The Nervous Text applet moves each letter around in a frantic, haphazard fashion.

Nervous text takes a string of text as its lone parameter. If not included, the default text is HotJava. You can also modify the applet's source code to achieve more flexibility, including controlling the size and color of the font.

To use this applet in a Web page, follow these steps:

  1. Move the insertion point to where you want to add the Nervous Text applet. Open the Java Applet Properties window.
  2. Set the Applet Source field to NervousText.class.
  3. Set the width field to the approximate pixel length of the text you want to animate. A good general width is 200.
  4. Set the height field to an appropriate height for the text size. A good general height is 50.
  5. Add a parameter. Set the name of the parameter to text. Set the value to the string you want to animate, such as Hello World.
  6. Close all open dialog boxes and save the page.

Nuclear Power Plant


This little simulation (see Figure 31.9) really doesn't seem useful, unless you plan to run power plants in Russia. It does, however, show a good example of a user interface, object interaction, and animation. After the applet is initialized, you can select one of three power-plant crises—from pump failures to blown turbines. To prevent a meltdown, open and close valves and start pumps as necessary. If you don't work quick enough, the core turns to mush and releases enough radioactivity to ruin everyone's day.

Figure 31.9. The Nuclear Plant applet, a creative use of Java as a learning tool and game implementation.

Applet Sources on the Web


There are many sources for applets on the Web that you can use. Make sure to check the licensing on the applet. Just because an applet appears on a page doesn't mean you can freely use it.

JavaSoft (http://java.sun.com/)


JavaSoft, a subsidiary of Sun Microsystems, handles the Java products. Go to its Web site (see Figure 31.10) first when looking for information, documentation, updates, downloads, and other feedback.

Figure 31.10. The JavaSoft home page includes links to the Java Developers Kit, HotJava, and other information of use to Java users and developers.

Originally part of the Sun Web site, JavaSoft received its own space to handle the dramatic increase in attention Java has received since its release.

JavaWorld (http://www.javaworld.com/)


The first online publication devoted entirely to Java, JavaWorld (see Figure 31.11) comes out monthly and includes news and views about Java developments, along with hands-on tips and tricks. Programming contests are a regular feature, and many articles include links to Java-powered sites, source code, and other helpful items.

Figure 31.11. JavaWorld includes interviews with the movers and shakers in the Java realm, along with hands-on examples, tutorials, and contests.

Gamelan (http://www.gamelan.com/)


The Gamelan site shows you what the rest of the world is doing with Java by maintaining a comprehensive list of links to applications and applets available on the Web. Links appear here to some of the best applets to date, and you can download some of them for use on your pages (see Figure 31.12). It also includes a page devoted to JavaScript for links devoted to pages utilizing Java's cousin.

Figure 31.12. Gamelan was developed specifically for the development and advancement of Java.

Some of the innovative productions found here include animators, tickers, network utilities, and a "Learn to Dance" applet.

Summary


Java use keeps spreading quickly as more and more hardware and software manufacturers pledge support to the language and concepts. Even if you never have the chance to delve deep into the intricacies of building an applet or application from scratch, an understanding of the basics will help you take full advantage of the powerful capabilities available.

Previous Page Page Top TOC Next Page