Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

JAVA Developer's Guide

Chapter 16 -- Web Programming With the java.applet Package

Chapter 16

Web Programming With the java.applet Package


CONTENTS


This chapter introduces the classes of the java.applet package and explains how applets are integrated within Web documents. It includes a short introduction to HTML. It describes how applets use window components and handle events and identifies the major phases in an applet's life cycle. Applet audio and animation capabilities are also covered. When you finish this chapter, you will have a good understanding of how applets work.

Applets and the World Wide Web

Applets are Java programs that are integrated in Web pages. When a Web page containing an applet is displayed by a Web browser, the applet is loaded and executed. The applet's output is displayed within a subset of the browser's display area. Figure 16.1 illustrates this concept.

Figure 16.1 :How an applet is displayed by a Web browser.

The Applet class is a subclass of the Panel class, and applets are implemented as a panel within a Web document. You'll learn more about the Panel class when you study window programming in Part IV, "Window Programming." Because the Applet class is a subclass of the Panel class, it inherits all the methods of the Panel class and is capable of using most window GUI components. In addition, applet events are handled in the same manner as in standalone Java window programs.

The Applet Class

The java.applet package is the smallest package in the Java API. It consists of a single class-the Applet class-and three interfaces: AppletContext, AppletStub, and AudioClip.

The Applet class contains a single default parameterless constructor, which is generally not used. Applets are constructed by the runtime environment when they are loaded and do not have to be explicitly constructed.

The Applet class contains 21 access methods that are used to display images, play audio files, respond to events, and obtain information about an applet's execution environment, referred to as the applet's context.

The getImage() and getAudioClip() methods are used to retrieve an Image or AudioClip object that is identified by an URL. The play methods are used to play an AudioClip object.

The init(), start(), stop(), and destroy() methods are used to implement each of the four life cycle stages of an applet. The init() method is invoked by the runtime environment when an applet is initially loaded. It is invoked to perform any required initialization processing. The start() method is invoked by the runtime system when an applet is initially started or restarted as a result of a user switching between Web pages. The stop() method is invoked by the runtime system when the user switches from the Web page containing the applet to another Web page or another program. The destroy() method is invoked when an applet's execution is terminated, usually as the result of the user exiting the browser. The isActive() method is used to determine whether an applet is currently active.



The getApplet Context() method is used to obtain the AppletContext object associated with an applet. The AppletContext interface defines methods by which an applet can access its execution environment. The getAppletInfo() method returns a String object that provides information about an applet. This information can include version, copyright, and authorship data as well as applet-specific data. The getAppletInfo() method is overridden by Applet subclasses to provide this information. The getCodeBase() method returns the base URL specifying the applet's location. The getDocumentBase() method returns the URL of the document in which the applet is contained. The getParameter() method is used to obtain parameter data that is passed to an applet in an HTML file. The getParameterInfo() method returns an array that describes all the parameters used by an object. It is overriden by Applet subclasses in the same manner as the getAppletInfo() method.

The resize() methods are used to resize an applet. The setStub() method is used to set the AppletStub associated with the applet. It should not be used unless you are constructing your own custom applet viewer. The showStatus() method is used to display a status message using the applet's context.

The AppletContext interface defines methods that allow an applet to access the context in which it is being run. This is typically a Web browser, such as Netscape, but could also be the applet viewer. The AppletContext interface of an applet is accessed using the getAppletContext() method of the Applet class. AppletContext provides seven methods that allow an applet to obtain information about and manipulate its environment. The getApplets() method returns an Enumeration object that contains all applets which are accessible in the applet's context. The getApplet() method returns an Applet object whose name matches a String parameter.The getAudioClip() method returns an AudioClip object that is referenced using an URL. The getImage() object returns an Image object that is identified by an URL. The two showDocument() methods are used to instruct a Web browser to display the Web document located at a particular URL. The showStatus() method is used to display a status message via the Web browser executing the applet.

The AppletStub interface is used to implement an applet viewer. It is not generally used by applets. It provides six methods that are used to retrieve applet parameters that can be used to support applet viewing.

The AudioClip interface defines three methods: play(), stop(), and loop(). The play() method is used to play an audio clip. The stop() method is used to terminate the playing of an audio clip. The loop() method is used to start and play an audio clip in a continuous loop.

Applets and HTML

Web documents are written in Hypertext Markup Language (HTML). HTML uses tags to describe the structure of Web documents. Tags are used to identify headings, paragraphs, and lists, as well as other elements of Web pages such as links, images, forms, and applets. In order to use applets in your Web documents, you need to learn about a few basic HTML tags. While a complete introduction to HTML is beyond the scope of this book, this section provides a quick summary of the basic HTML tags that you will need to work the examples in this book.

Note
For more information on HTML, point your Web browser at the URL http://www.jaworski.com/htmlbook/. Here you'll find links to introductory tutorials on HTML as well as links to more advanced HTML topics.

Using HTML Tags

HTML tags begin with a < and end with a >. The name of the tag is placed between the opening < and closing >. The tag name may be written using any combination of upper- or lowercase characters. I use the convention of writing tags in uppercase to set them apart from the text to which they apply. For example, the title tag is written <TITLE>, the head tag is written <HEAD>, and the body tag is written <BODY>.

HTML supports two types of tags-separating tags and surrounding tags. Separating tags are placed between the text elements to which they apply. For example, the break tag, written <BR>, is used to insert a line break within a line of text. It is placed at the point in the line where the break is desired, as shown in the following HTML:

This line ends at the break tag.<BR>This text is displayed on the next line.

Surrounding tags consist of pairs of tags that surround the text to which they apply. The first tag in the pair is referred to as the opening tag and the second tag is referred to as the closing tag. The closing tag contains a / between the opening < and the tag's name. Examples of surrounding tags are <HTML> and </HTML>, <HEAD> and </HEAD>, and <BODY> and </BODY>. You'll learn about these tags in subsequent sections.

Some HTML tags are allowed to specify attributes. Attributes are used to identify properties of the tag and are included in the tag between the tag name and the closing >. When attributes are used with surrounding tags, they are included in the opening tag, but not in the closing tag. For example, the applet tag uses attributes to identify the name of the class to be loaded, the dimensions of the applet display region within the browser window, and other properties of the applet. The following HTML is an example of an applet tag that uses attributes:

<APPLET CODE="TestApplet" WIDTH=300 HEIGHT=300>
[alternate text to be displayed]
</APPLET>

The opening applet tag has three attributes: CODE, WIDTH, and HEIGHT. The CODE attribute has the value of "TestApplet" and identifies the name of the applet's bytecode file. The WIDTH and HEIGHT attributes both have the value 300 and specify a 300¥300 pixel applet display region within the browser window. The text [alternate text to be displayed] appearing between the opening and closing applet tags identifies text that a browser should display if it does not support Java applets.

The HTML, Head, and Body Tags

HTML documents are written in ASCII text. The <HTML> and </HTML> tags mark the beginning and end of an HTML document. HTML documents consist of a single head and a single body. The head is used to identify information about an HTML document, such as its title, while the body contains the information displayed by the HTML document. The head and body are identified using the <HEAD> and </HEAD> and <BODY> and </BODY> tags. The following HTML illustrates the use of these tags:

<HTML>
<HEAD>
The document title appears here.
</HEAD>
<BODY>
The information displayed by the HTML document appears here.
</BODY>
</HTML>

The Title Tag

The title of an HTML document is typically displayed at the top of the browser window, as shown in Figure 16.2. The title is placed in the head of a Web document and is surrounded by the <TITLE> and </TITLE> tags.

Figure 16.2 :The title of a Web document.

The HTML used to create the Web page is shown in Listing 16.1.


Listing 16.1. Using the title tag.

<HTML>
<HEAD>
<TITLE>This is the document title</TITLE>
</HEAD>
<BODY>
This is the document body.
</BODY>
</HTML>


The Heading and Paragraph Tags

The heading and paragraph tags are the most common tags found within the body of a Web document. The heading tags are used to specify document headings. These headings are used to organize Web documents into sections and subsections in the same manner in which the chapters of this book are organized into sections and subsections. HTML supports six heading levels. First-level headings are identified by the <H1> and </H1> tags, second-level headings are identified by the <H2> and </H2> tags, and so on. Sixth-level headings are identified by the <H6> and </H6> tags. The HTML in Listing 16.2 shows how all six heading levels are displayed.


Listing 16.2 Using heading tags.

<HTML>
<HEAD>
<TITLE>HTML Headings</TITLE>
</HEAD>
<BODY>
<H1>Heading Level 1</H1>
<H2>Heading Level 2</H2>
<H3>Heading Level 3</H3>
<H4>Heading Level 4</H4>
<H5>Heading Level 5</H5>
<H6>Heading Level 6</H6>
</BODY>
</HTML>


Figure 16.3 shows how this HTML file is displayed by my Web browser.

Figure 16.3 :HTML heading levels.

Paragraph tags are used to mark paragraphs within HTML documents. In HTML, spaces, tabs, carriage returns, and line feeds are referred to as whitespace characters. One or more whitespace characters are normally displayed as a single space by Web browsers. In order to mark the beginning and end of a paragraph, the HTML paragraph tags, <P> and </P>, must be used. For example, the HTML shown in Listing 16.3 illustrates the use of paragraph tags. Figure 16.4 shows how this HTML is displayed by a Web browser.

Figure 16.4 :HTML paragraphs.


Listing 16.3. Using paragraph tags.

<HTML>
<HEAD>
<TITLE>HTML Paragraphs</TITLE>
</HEAD>
<BODY>
<H1>How paragraphs are marked in HTML</H1>
<P>This is paragraph 1.</P><P>This is paragraph 2.</P>
<P>This is paragraph 3.
This text also belongs to paragraph 3.
Notice that carriage returns and      multiple spaces     do
not affect the way paragraphs are formatted.</P>
</BODY>
</HTML>


The paragraph tag can also be written as a single separating tag, <P>, although this is considered bad practice. The previous example could also have been written as shown in Listing 16.4 using separating paragraph tags rather than surrounding paragraph tags. Figure 16.5 shows how it is displayed by my Web browser.

Figure 16.5 :Marking HTML paragraphs with separating tags.


Listing 16.4. Using paragraph tags as separating tags.

<HTML>
<HEAD>
<TITLE>HTML Paragraphs using separating tags</TITLE>
</HEAD>
<BODY>
<H1>How paragraphs are marked in HTML</H1>
This is paragraph 1.<P>This is paragraph 2.
<P>This is paragraph 3.
This text also belongs to paragraph 3.
Notice that carriage returns and      multiple spaces     do
not affect the way paragraphs are formatted.
</BODY>
</HTML>


The Applet and Parameter Tags

While there are a number of different HTML tags that you can learn, the applet and parameter tags are the primary tags of interest for Web programmers.

The applet tag is a surrounding tag. It may surround zero or more parameter tags. It may also surround alternative text. Alternative text is text that appears between the <APPLET> and </APPLET> tags that is not included in a parameter tag. It is displayed by browsers that are not Java enabled as an alternative to the applet's display.

The parameter tag is used to pass named parameters to a Java applet. It is a separating tag that has two attributes: NAME and VALUE. The NAME attribute identifies the name of a parameter and the VALUE attribute identifies its value. The following are examples of the use of parameter tags:

<PARAM NAME="speed" VALUE="slow">
<PARAM NAME="duration" VALUE="long">
<PARAM NAME="delay" VALUE="short">

An applet uses the getParameter() method of the Applet class to retrieve the value of a parameter. The parameter tag may only appear between the <APPLET> and </APPLET> tags.

The applet tag supports nine attributes: ALIGN, ALT, CODE, CODEBASE, HEIGHT, HSPACE, NAME, VSPACE, and WIDTH.

The ALIGN attribute specifies the alignment of an applet's display region with respect to the rest of the line being displayed by a browser. This line may consist of text, images, or other HTML elements. Values for this attribute are TOP, TEXTTOP, BOTTOM, ABSBOTTOM, BASELINE, MIDDLE, ABSMIDDLE, LEFT, and RIGHT. The TOP attribute value causes the top of an applet to be aligned with the top of the line being displayed by a browser. The TEXTTOP attribute causes the top of an applet to be aligned with the top of the text being displayed in the current line. The BASELINE and BOTTOM attributes cause the bottom of the applet to be aligned with the baseline of the text in the line being displayed. The ABSBOTTOM attribute causes the bottom of an applet to be aligned with the bottom of the current line being displayed. The MIDDLE attribute causes the middle of the applet to be aligned with the middle of the text displayed in the current line. The ABSMIDDLE attribute causes the middle of the applet to be aligned with the middle of the line being displayed. The LEFT and RIGHT attributes causes the applet to be aligned at the left and right margins of the browser window.

The ALT attribute identifies text that should be displayed by a browser if it understands the applet tags, but does not support Java applets or has applet processing disabled.

The CODE attribute is a relative URL that identifies the name of the bytecode file of the applet.

Normally, the URL of the Web document displaying the applet is used as the base URL for locating the bytecode file referenced by the CODE attribute. The CODEBASE attribute is used to change the base URL to another location.

The HEIGHT attribute identifies the height of the display area required by the applet.

The HSPACE attribute specifies the number of pixels to be used as the left and right margins surrounding an applet.

The NAME attribute is used to assign a name to an applet. This name is used to support inter-applet communication.

The VSPACE attribute specifies the number of pixels to be used as the top and bottom margins surrounding an applet.

The WIDTH attribute identifies the width of the display area required by the applet.

Of the nine applet attributes, only the CODE, HEIGHT, and WIDTH attributes are required.

The HTML file sample.htm, which is shown in Listing 16.5, shows how an applet may be specified in a Web document.


Listing 16.5. The sample.htm file.

<HTML>
<HEAD>
<TITLE>Using the Applet Tag</TITLE>
</HEAD>
<BODY>
<H1>An Applet that Displays Text at a Designated Location</H1>
<APPLET CODE="SampleApplet.class" HEIGHT=300 WIDTH=300>
<PARAM NAME="text" VALUE="Applets are fun!">
<PARAM NAME="x" VALUE="50">
<PARAM NAME="y" VALUE="50">
Text displayed by browsers that are not Java-enabled.
</APPLET>
</BODY>
</HTML>


The applet specified in the applet tag displays the text Applets are fun! at the coordinate 50,50 within the 300¥300 pixel applet display area, as shown in Figure 16.6.

Figure 16.6 :The display of sampleApplet

The source code of the SampleApplet applet is provided in Listing 16.6.


Listing 16.6. The SampleApplet.java source code file.

import java.applet.*;
import java.awt.*;

public class SampleApplet extends Applet {
 String text = "error";
 int x = 0;
 int y = 20;
 public void init() {
  text = getParameter("text");
  try {
   x = Integer.parseInt(getParameter("x"));
   y = Integer.parseInt(getParameter("y"));
  }catch(NumberFormatException ex){
  }
 }
 public void paint(Graphics g) {
  g.setFont(new Font("TimesRoman",Font.BOLD+Font.ITALIC,36));
  g.drawString(text,x,y);
 }
}


You can compile SampleApp.java using the command javac SampleApplet.java. Create the sample.htm file shown in Listing 16.5 and store it in your \java\jdg\ch16 directory. Then open the sample.htm file using your Web browser. This should result in a display similar to that shown in Figure 16.6.

The SampleApplet class extends the Applet class. It declares three field variables: text, x, and y. The text variable is used to hold the text that is displayed in the Applet display area. The x and y variables specify the location where the text is to be displayed. The default value of the text variable is set to "error". The default value of the x variable is set to 0. The default value of the y variable is set to 20.

The init() method is invoked by the Java runtime system to perform any required initialization. The init() method uses the getParameter() method of the Applet class to get the value of the text, x, and y parameters. The parseInt() method of the Integer class is used to convert the String value returned by the getParameter() method to an into value.

The paint() method is invoked by the Java runtime system to update the Java display area. It is automatically passed a Graphics object as a parameter. This object is used to draw on the applet's display area. The paint() method uses the setFont() method of the Graphics class to set the current font to a 36-point bold italic TimesRoman font. The drawString() method of the Graphics class is used to display the value of the text variable at the x,y coordinate.

Other HTML Tags

The HTML tags covered in the preceding sections are the minimum needed to get you started using applets with HTML documents. There are many more HTML tags that you can use with your Web pages. The URL http://www.jaworski.com/jdg contains links to Web documents that describe these other HTML tags.

The Life Cycle of an Applet

An applet has a well-defined life cycle, as shown in Figure 16.7. Applets do not need to be explicitly constructed. They are automatically constructed by the runtime environment associated with their applet context-a Web browser or the applet viewer. The init() method provides the capability to load applet parameters and perform any necessary initialization processing. The start() method serves as the execution entry point for an applet when it is initially executed and restarted as the result of a user returning to the Web page that contains the applet. The stop() method provides the capability to stop() an applet's execution when the Web page containing the applet is no longer active. The destroy() method is used at the end of an applet's life cycle to perform any termination processing.

Figure 16.7 :The stages of an applet's life cycle.

Responding to Events

Because the Applet class is a subclass of the Panel class and therefore part of the window class hierarchy, applets handle events in the same manner as other window components. All the window event handling approaches that you will learn in Part IV will also apply to Applet event handling. The init(), start(), stop(), and destroy() methods that you covered in the previous section are used to handle events that are generated by the Java runtime system. These methods are specific to applets and do not apply to other window components.

Using Window Components

Since the Applet class is a subclass of the Panel class, it can use most of the GUI components that are used by standalone window programs. This includes labels, buttons, checkboxes, radio buttons, lists, text components, canvases, and scrollbars. You will learn to use these components in Part IV. The only major GUI components that cannot be used within an applet are menu components. Menu components are attached to Frame objects, which are associated with an application window. It is possible for an applet to create and open a separate application window in the form of a Frame object, however such an application window would be labeled as untrusted in accordance with the applet security policy. This prevents the window from masquerading as other programs running on the user's system.

Adding Audio and Animation

The Applet class provides the capability to play audio files. These files must be in the Sun audio format and usually end with the .au extension. The play() method of the Applet class can be used to play an audio file that is identified by an URL. A more flexible approach is to load an object that implements the AudioClip interface and then invoke the object's play(), loop(), and stop() methods. The getAudioClip() method can be used to load an audio file by identifying its URL.

Java also supports the capability to include animation in standalone window programs and applets. Chapter 25, "Using Animation," covers this topic.

Summary

This chapter introduces the classes of the java.applet package and explains how applets are integrated within Web documents. It describes how applets use window components and handle events. The major phases in an applet's life cycle are introduced. Applet audio and animation capabilities are also covered. Part VI, "Programming the Web with Applets and Scripts," provides a detailed tutorial on applet programming.