Notice: This material is excerpted from Special Edition Using Java, ISBN: 0-7897-0604-0. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.
by Kevin M. Krom
In the last several chapters, you learned how to create a Java applet. Or maybe you just want to use a pre-written applet in one of your documents. When the time comes to test your applet, and then later to show it to others, you're going to need to place your applet inside an HTML file so it can be viewed it with a Web browser or the appletviewer program.
In this chapter you will learn how:
Adding items to an HTML document is done through the use of tags. For example, if you wanted to insert a GIF image file called "somepic.gif," you would put the following in your HTML source document:
<IMG src="somepic.gif">
Note that the <IMG> tag is case insensitive, i.e., "IMG" and "img" both work. Likewise, both "SRC" and "src" will work for the image source parameter.
However, using the All Caps form of HTML tags may make reading your HTML source easier, as the tags will stand out clearly from parameters and plain text.
Including a Java applet is done in a similar fashion to images through the use of the <APPLET> tag. The basic syntax of the <APPLET> tag is:
<APPLET [codebase=[path|URL]] code=someclass.class height=applet_height width=applet_width> </APPLET>
As with the <IMG> tag, the <APPLET> tag is case insensitive, except the values of someclass.class, path, and URL.
Why does the <APPLET> tag needs a closing </APPLET> tag?
This is not the complete syntax of the <APPLET> tag. In order to specify user parameters for the applet or alternate HTML for browsers which aren't Java-enabled, the applet declaration needs to be bracketed to include potentially any number of other tags inside of it.
The full <APPLET> syntax is specified later in this chapter.
The codebase parameter specifies the location of the class file. The value of codebase can either be a pathname relative to the HTML file, or it can be a uniform resource locator (URL) specifying the location of the class.
This parameter is technically optional, but is always needed if the applet's .class file is not in the same directory as the referencing HTML file.
For this example, the Foo.class file is located in a subdirectory classes directly underneath the directory Foo.html is located in figure 19.1 (the left side) shows this directory structure. Foo.html then needs to use the codebase parameter to specify the classes subdirectory:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> </APPLET>
To access a remote class, use the codebase to specify the URL of the directory which contains the class, not the URL of the class itself. To access a Foo.class on the fictitious remote machine example.applet.net, whose directory layout is shown on the right side of figure 19.1:
<APPLET codebase="http://example.applet.net/html/classes" code="Foo.class" height=100 width=300> </APPLET>
Fig. 19.1 Location of the Foo.class file for both local (left) and remote (right) applet calls.
The code parameter specifies the name of the applet class to be executed. For example, if you want to include the applet in the file Foo.class in the same directory as your HTML file, you simply need to specify:
<APPLET code="Foo.class" height=100 width=300> </APPLET>
The quotes around the class name are not strictly necessary, but they help maintain good style and consistency.
Test the applet by using appletviewer, included with the Java release, or with Netscape Navigator. To use the appletviewer from the command line, enter the command:
appletviewer Foo.html
Assuming, of course, that you've used Foo.html as the name of your HTML file.
With Netscape Navigator or other Java-enabled browser, simply load the HTML file in the normal manner. For Netscape Navigator, select File->Open File (or use the shortcut Ctrl-O) and then find the correct file to load.
Windows 95/NT users need to open a DOS window to get a command line, and should be in the directory with the HTML file, rather than using an absolute or relative pathname.
The height and width parameters are both required, andspecify how tall or how wide (respectively) the applet will appear in number of pixels. If you want Foo.class to be 300 pixels wide by 100 pixels high, your HTML tag would look like:
<APPLET codebase="classes" code="Foo.class" width=300 height=100> </APPLET>
To add an applet to an HTML document:
Applets receive their initialization parameters through the invoking HTML file. In the previous section, you saw the pre-defined parameters code, codebase, height, and width. In this section, you'll learn how to pass additional parameters to applets via the <PARAM> tag.
The syntax for applets with user-specified parameters:
<APPLET [codebase=[path|URL]] code=someclass.class height=applet_height width=applet_width> {[<PARAM name=paramter_name value=parameter_value>]} </APPLET>
The entire <PARAM> tag, except parameter_value, is case insensitive. Whether parameter_value is case sensitive or not depends on the code which uses it. By default, parameter_value is case sensitive.
The <PARAM> tag needs to be place between the <APPLET> and </APPLET> tags for the applet it corresponds to. You can use as many different <PARAM> tags as you wish for each applet, each one specifying a different applet parameter.
When you write an applet, you can search for any number of parameters, of which some, all, or none may be present when the applet is declared in the HTML file. Take Foo.java as the example source. Inside of the init() method, it has code to handle two parameters: color and text.
The getParameter() method allows the programmer to access the parameters specified by the <PARAM> tags. The method always returns a String, and needs to be supplied with the (case-insensitive) name of the parameter to be read. Note the first line of the init() method below-it reads the "COLOR" parameter.
public void init() { String p = getParameter("COLOR"); if (p == null) { textcolor = Color.black; } else if (p.equalsIgnoreCase("red")) { textcolor = Color.red; } p = getParameter("TEXT"); if (p == null) { textvalue = "Hello world."; } else { textvalue = p; }}
Note that by using the equalsIgnoreCase method (from class String), this applet has made the color parameter case insensitive.
This is only part of the Foo.java file. The full source code is listed toward the end of the chapter.
/examples/chapter19/Foo.java (\examples\chapter19\Foo.java for Windows NT and Windows 95 users)
With the above initializers, a Foo applet will print the phrase "Hello world." in black if no other parameters are given:
Fig. 19.2 Foo applet without parameters.
To change the color of the text to red, you can insert a <PARAM> tag, changing the value of the color parameter:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> <PARAM name=color value="red"> </APPLET>
And now, to change the text to something else, like "I love creating Java applets!", add another <PARAM> tag:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> <PARAM name=color value="red"> <PARAM name=text value="I love creating Java applets!"> </APPLET>
Fig. 19.3 Foo applet with text set to "I love creating Java applets!"
All parameters are passed to the init method of the applet, regardless of whether or not there is any code written to handle the parameter. As a demonstration, add a third parameter to the applet declaration:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> <PARAM name=color value="red"> <PARAM name=dummy value="bogus"> <PARAM name=text value="I love creating Java applets!"> </APPLET>
The result is exactly the same as before. Since there is nothing to handle the dummy parameter, it is simply ignored, without affecting anything else.
To add an applet to an HTML document (updated):
As of this writing, the only browser which supports the finalized 1.0 version of Java is Netscape Navigator 2.0, by Netscape Corporation. While this is one of the more popular Web browsers (perhaps even the most popular), there are people out there using other browsers who will not get to see your Java applets.
The HTML parser in these browsers will simply skip over the <APPLET> and <PARAM> tags, since they don't have the capability to display them. Most, if not all, won't even recognize these tags as valid HTML. The point is, the rest of the document will be displayed.
You may wish to include something for these browsers, because it's possible certain things may be out of context once the applet is missing, or perhaps you just want whoever is viewing the page to know that there's more than meets their browser's eye.
This is the other reason that the </APPLET> closing tag is needed. Anything within the bracketed applet tags will be displayed to the user only if it is a non-Java browser. To display any other HTML test, images, etc., specify the HTML source for these browsers between the <APPLET> and </APPLET> tags of the appropriate applet. This is the final syntax for an HTML applet declaration:
<APPLET [codebase=[path|URL]] code=someclass.class height=applet_height width=applet_width> {[html|<PARAM name=paramter_name value=parameter_value>]} </APPLET>
The html can occur before, after, around, or even in between your group of <PARAM> tags. For good style and cleanliness, place the alternate HTML after all of your <PARAM> tags, if any.
This is not the complete syntax of the <APPLET> tag, but this should be all you need to use most, if not all, of the time. For the complete syntax, see the README file distributed with the JDK.
Java-enabled browsers will simply ignore the html, while non-Java browsers will ignore everything but the html. You can add a "consolation" message to the Foo applet for non-Java enabled viewers like so:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> <PARAM name=color value="red"> <PARAM name=text value="I love creating Java applets!"> You don't have a <strong>Java</strong>-enabled browser!<p> </APPLET>
Attempting to view this HTML from a non-Java browser (such as the 1.0 alpha 3 HotJava browser) looks something like:
Fig. 19.4 Foo applet as viewed by a non-Java browser.
To add an applet to an HTML document (updated):
At the time of this writing, the latest version of the HotJava browser accepts only applets written in the 1.0 alpha 3 release of the language. If you plan on viewing applets inside of HotJava, make sure you write the source code using that release.
Applets written for any of the beta releases or the finalized 1.0 version of the language will not be viewable inside the HotJava browser.
The <APPLET> and <PARAM> tags were added in the beta releases. The original HTML tag was the <APP> tag:
<APP class=someclass {[param=val]}>
Note that since there is no corresponding </APP> tag, alternate HTML cannot be included. Parameters are included inside the <APP> tag, rather than through the use of <PARAM> tags.
The someclass parameter is the name of the applet class (minus the .class extension) to be executed. The parameters param and value are optional.
For a version of Foo written with the alpha 3 release, which called Foo_a3, the same applet declaration used earlier can be rewritten as:
<APP class="Foo_a3" color="red" text="I love creating Java applets!">
Fig. 19.5 The alpha 3 version of the Foo applet as viewed in HotJava.
The Foo_a3.class file must be stored in a subdirectory directly underneath the HTML file, and the name of that subdirectory must be classes.
If you're trying to use HotJava without an active TCP/IP stack, make sure your files are stored in a directory under the base hotjava directory. (Solaris users can use symbolic links to achieve this effect.)
Now, you just need to fire up the HotJava browser, and check out your handiwork.
So now you have an alpha 3 applet for HotJava users, and the same applet written with the final 1.0 release for Netscape Navigator users. If you want to present the correct version to the appropriate viewer, with no alternate text for non-Java viewers, you can simply use the <APP> tag as your alternate HTML:
<APPLET codebase="classes" code="Foo.class" height=100 width=300> <PARAM name=color value="red"> <PARAM name=text value="I love creating Java applets!"> <APP class=Foo_a3 color="red" text="I love creating Java applets!"> </APPLET>
So what, exactly, does the browser do when it comes across the <APPLET> tag? First it loads the bytecode for the specified class, then it attempts to run the applet.
A Java browser, or more precisely, the Java run-time environment inside the browser, is dynamically extensible, which means that it can add class definitions on the fly. That's what happens when an applet class is loaded-the class actually becomes part of the run-time system.
The Java-enabled browser is then free to create an instance of the applet class, and place it inside of the browser. The initializer will make all of the parameters (specified by the <PARAM> tag) available to the applet.
The browser contains one or more objects to handle bytecode verification and security. If the bytecode doesn't meet the validation checks, the run-time Java environment inside of the browser will reject the byte code, and the class will not be loaded. An appropriate error or warning message will inform you when this occurs.
Likewise, the run-time environment will not allow an applet to violate any security provisions while the applet is running. The response of the browser is somewhat variable, based on the security policy set for the user's system.
See "Before We Begin: Java & Security" Chapter 6 for more information about Java run-time security.
If the applet uses additional resources, such as images, audio, or other classes, these are loaded by the browser as needed by the applet, providing the browser hasn't already had to load the resource previously for another applet.
Additional classes, used as resources by an applet, are also subject to byte code verification and security measures.
Using Packages to Avoid Namespace Conflicts
If a class has already been loaded, the Java run-time will attempt to use that class rather than go through the overhead of loading it in again. This can create problems if multiple classes have the same name.
To avoid namespace conflicts, you might want to use packages.
For information about packages, see "The Parts of the Language" Chapter 7.
To make sure your Foo applet doesn't create problems if another Foo class comes along, put it in a package called, for example, "SEJava". Figure 19.6 shows the directory layout for using the ficticious SEJava package structure.
Fig. 19.6 Directory structure for the SEJava package.
When writing the HTML code to create the applet, use SEJava.Foo.class as the class name, like so:
<APPLET codebase="classes" code="SEJava.Foo.class" height=100 width=300> etc.
Once the byte code is verified, the Java run-time calls the init() method to give the applet a chance to initialize its resources. Since init() will only be invoked once, this is the best time to do initialization and preparation for the applet instance, such as parsing and storing information from the parameters.
After init() is called, the Java run-time calls start(). As seen below, start() and stop() can be called many times during an applet's lifetime. As such, start() is the best place to create threads, since the threads should be released by stop().
Fig 19.7 An applet's state transition diagram (STD).
The lifecycle of an applet is fairly straightforward, as shown by figure 19.7 (above). It is based on the inherited methods shown in the diagram. Note that the paint() method doesn't change the state of the applet at all. It only makes sense for paint() to be called when the applet is in the "Started" state.
See "The Basics of Applet Construction", Chapter 15, for more details about the methods defined by the Applet class.
The browser calls the stop() method on the applet when it changes to a new page, or when it reloads the current page (see note below). However, it is up to the author of the applet to actually stop the applet's execution within the stop() method.
When the browser returns to a page with an already loaded applet, it restarts the applet with the start() method again.
What does the browser do with applets when it reloads the page?
This turns out to be browser-specific. Some, such as the appletviewer utility, actually reload the applet, which means that the current applet is cleaned up by stop() and destroy(), and then the applet goes through the entire process from the beginning. Others, like Netscape Navigator, will not reload the applet, but instead they will just stop() and then start() the applet again.
Some applets, such as the Foo applet in this chapter, don't really do anything after they've been started, but many applets will have one or more threads running at any given time. If the stop() method doesn't contain code to suspend the current execution, the applet will continue to run, and that could start affecting the user's performance, especially if several applets continue to run unchecked.
To summarize, for applets that "run," the start() method creates the thread or threads which the applet will run in, and the stop() method should stop and then release the thread or threads. (Threads can be released by setting them to null.)
For more information on threads, see "More About Java Applications" Chapter 25.
When the time comes for an applet to be deleted, it gets released in two stages. Just like creating an applet calls both the init() and start() methods, deleting an applet will first stop() the applet, then it will destroy() it.
Since stop() should clean up all of the threads, it's unlikely that destroy() actually needs to be over-written by your applet. However, there are some cases, such as in inter-process communication, where it may be desirable to have a more controlled shutdown. In most cases, however, it is probably best to stick with the default destroy() method.
A Java-enabled browser loads the applet class, and its required resources, at run-time, when the HTML source containing the applet declaration is read.
The Java run-time then calls the initialization function init(), at which time the parameters are available to be processed by the applet.
After initialization, the applet is started with the start() method. The browser draws the applet by calling the paint() method.
When the browser is minimized, or the page is exited, it should invoke the stop() method on the applet.
When an applet is deleted, the Java run-time first uses stop() and then destroy() to clean up the applet's resources.
import java.awt.*; public class Foo extends java.applet.Applet { Color textcolor; String textvalue; public void init() { String p = getParameter("COLOR"); if (p == null) { textcolor = Color.black; } else if (p.equalsIgnoreCase("blue")) { textcolor = Color.blue; } else if (p.equalsIgnoreCase("green")) { textcolor = Color.green; } else if (p.equalsIgnoreCase("red")) { textcolor = Color.red; } else { System.out.println("Invalid color... exiting"); System.exit(0); } p = getParameter("TEXT"); if (p == null) { textvalue = "Hello world."; } else { textvalue = p; } } public void paint(Graphics g) { g.setColor(textcolor); g.drawString(textvalue, 50, 50); } }
import browser.Applet; import awt.Graphics; class Foo_a3 extends Applet { awt.Color textcolor; String textvalue; public void init() { String att = getAttribute("color"); if (att == null) { textcolor = awt.Color.black; } else if (att.equalsIgnoreCase("blue")) { textcolor = awt.Color.blue; } else if (att.equalsIgnoreCase("green")) { textcolor = awt.Color.green; } else if (att.equalsIgnoreCase("red")) { textcolor = awt.Color.red; } else { System.out.println("Invalid color... exiting"); System.exit(0); } att = getAttribute("text"); if (att == null) { textvalue = "Hello world."; } else { textvalue = att; } } public void paint(Graphics g) { g.setForeground(textcolor); g.drawString(textvalue, 50, 25); } }
Most of the material in the section covering the lifecycle of an applet was verified by comparison to the tutorial pages written by the Java team at:
For technical support for our books and software contact support@mcp.com
Copyright ©1996, Que Corporation