'; zhtm += ''; zhtm += '

' + pPage + ''; zhtm += '
'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 } //--> Java 1.2 Unleashed -- Ch 5 -- JDK 1


Java 1.2 Unleashed

Contents


- 5 -

JDK 1


JDK 1.2 Applet Writing Basics

This chapter introduces the classes of the java.applet package and explains how applets are integrated within Web documents using the HTML <APPLET> tag. It describes how applets use window components and identifies the major phases in an applet's life cycle. Applet audio capabilities, JavaBeans, and Java Plug-In 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 into 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 5.1 illustrates this concept.

FIGURE 5.1. How an applet is displayed by a Web browser.

The Applet class is a subclass of the Panel class, and an applet is implemented as a panel within a Web document. You'll learn more about the Panel class when you study window programming in Chapter 9, "Creating Window Applications." 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 one of the smallest packages 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 23 methods that are used to display images, play audio files, respond to events, and obtain information about an applet's execution environment (or 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 audio files at specified URLs. JDK 1.2 introduces the newAudioClip() method, a static method that allows AudioClip objects to be created without an applet context.


NOTE: The newAudioClip() method is the only new Applet method introduced with JDK 1.2.

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 started, or when it's 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 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 getAppletContext() 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() 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 overridden 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 getLocale() method returns the Locale object associated with the applet. It is used to support language-independent applet programming.

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 Navigator or Microsoft Internet Explorer, 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 that 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() method 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 information that can be used to support applet viewing.

The AudioClip interface defines three methods: play(), stop(), and loop(). The play() method plays an audio clip. The stop() method terminates the playing of an audio clip. The loop() method starts and plays an audio clip in a continuous loop.

A Brief HTML Primer

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. Although 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 use the examples in this book.


NOTE: For more information on HTML, point your Web browser to 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 >, and the name of the tag is placed between them. The tag name may be written using any combination of upper- or lowercase characters. I write 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 the opening tag and the second tag is 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.class" 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.class" 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, with the <HTML> and </HTML> tags marking the beginning and end. They consist of a single head and a single body. The head is used to identify information about the 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>, </HEAD>, <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 5.2. The title is placed in the head of the Web document and is surrounded by the <TITLE> and </TITLE> tags.

FIGURE 5.2. The title of a Web document appears in the title bar at the top of the window.

The HTML used to create the Web page in Figure 5.2 is shown in Listing 5.1.

LISTING 5.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, which in turn 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. The HTML in Listing 5.2 shows how all six heading levels are displayed.

LISTING 5.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 5.3 shows how this HTML file is displayed by my Web browser.

FIGURE 5.3. HTML heading levels.

Paragraph tags are used to mark paragraphs within HTML documents. Spaces, tabs, carriage returns, and line feeds are referred to as whitespace characters in HTML. 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. The HTML shown in Listing 5.3 illustrates the use of paragraph tags. Figure 5.4 shows how this HTML is displayed by a Web browser.

LISTING 5.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>

FIGURE 5.4. HTML paragraphs.

The paragraph tag may also be written as a single separating tag, <P>, although this is considered bad form. The previous example could also have been written to display identically using separating paragraph tags rather than surrounding paragraph tags.

The <APPLET> and Parameter Tags

Although there are a number of different HTML tags that you can learn, the <APPLET> and parameter tags are the primary tags of interest to 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 11 attributes: ALIGN, ALT, ARCHIVES, CODE, CODEBASE, HEIGHT, HSPACE, NAME, OBJECT, VSPACE, and WIDTH.

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

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

LISTING 5.4. 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 coordinates 50,50 within the 300¥300 pixel applet display area, as shown in Figure 5.5.

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

LISTING 5.5. 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);
 }
}

Compile SampleApp.java using the command javac SampleApplet.java. Then open the sample.htm file using your Web browser. This should result in a display similar to that shown in Figure 5.5.

FIGURE 5.5. The display of SampleApplet.

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 int 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 5.6. Applets do not need to be explicitly constructed. They are automatically constructed by the runtime environment associated with their applet context--the Web browser or 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.

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 for window applications will also apply to Applet event handling. The init(), start(), stop(), and destroy() methods that were 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.

FIGURE 5.6. The stages of an applet's life cycle.

Using Window Components

Because 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 the next chapter. 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, but such an application window would only be trusted to the extent allowed by the applet security policy. This prevents the window from masquerading as other programs running on the user's system.

Adding Multimedia Features

The Applet class provides the capability to display images and play audio files. Images are displayed on the Canvas object associated with the applet's display area. Before JDK 1.2, applets only supported audio files that were in the Sun audio format (.au files). JDK 1.2 introduces a new sound engine and the capability to play audio files in both applets and applications. The new sound engine supports the following audio file formats:

Support for the preceding formats greatly enhances the audio capabilities of Java applets and applications.

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.

The JDK 1.2 also introduced the newAudioClip() method of the Applet class. This static method allows AudioClip objects to be created independently of an applet context, reducing the dependency of applets on the capabilities provided by differing browsers.

In addition to image display and audio playback, Java also provides the capability to include animation in applets and standalone window programs. Chapter 22, "Creating Animations," covers this topic.

An Audio Player Applet

The AudioPlayer applet, developed in this section, shows how easy it is to include multimedia features in applets. The source code for the AudioPlayer applet is shown in Listing 5.6.


NOTE: You need a sound board and speaker(s) to run this applet. You also need to be connected to the Internet.

LISTING 5.6. THE SOURCE CODE OF THE AudioPlayer APPLET.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class AudioPlayer extends Applet {
 AudioClip music;
 Image background;
 public void init() {
URL codeBase = getCodeBase();
  music = getAudioClip(codeBase,"spacemusic.au");
  background = getImage(codeBase,"space.gif");
  setLayout(new BorderLayout());
  Panel buttons = new Panel();
  Button playButton = new Button("Play");
  Button stopButton = new Button("Stop");
  Button loopButton = new Button("Loop");
  playButton.addActionListener(new ButtonHandler());
  stopButton.addActionListener(new ButtonHandler());
  loopButton.addActionListener(new ButtonHandler());
  buttons.add(playButton);
  buttons.add(stopButton);
  buttons.add(loopButton);
  add("South",buttons);
 }
 public void stop() {
   music.stop();
 }
 public void paint(Graphics g) {

g.drawImage(background,0,0,this);

 }
 class ButtonHandler implements ActionListener {
  public void actionPerformed(ActionEvent e){
   String s = e.getActionCommand();
   if("Play".equals(s)) music.play();
   else if("Stop".equals(s)) music.stop();
   else if("Loop".equals(s)) music.loop();
  }
 }
}

Compile AudioPlayer.java using javac AudioPlayer.java. The HTML file that is used to display the applet is shown in Listing 5.7. Note that the CODE, WIDTH, and HEIGHT attributes of the applet have been specified. You will need two additional files to run the applet: space.gif and spacemusic.au. These files are located in the ch05 directory.

LISTING 5.7. THE audio.htm FILE.

<HTML>
<HEAD>
<TITLE>Audio Player</TITLE>
</HEAD>
<BODY>
<APPLET CODE="AudioPlayer.class" WIDTH=300 HEIGHT=350>
[AudioPlayer applet]
</APPLET>
</BODY>
</HTML>

Open the audio.htm file with appletviewer using the following command:

appletviewer audio.htm

The appletviewer will create a window display similar to the one shown in Figure 5.7.

FIGURE 5.7. The audio.htm file, as displayed by appletviewer.

You can also use your browser to load the applet over the Internet. The audio.htm, AppletViewer.class, AppletViewer$ButtonHandler.class, space.gif, and spacemusic.au files are located in the \java directory of my Web server. Use your browser to go to http://www.jaworski.com/java/audio.htm. It will display the window shown in Figure 5.8.

Your browser loads the audio.htm file and then the AudioPlayer.class and AudioPlayer$ButtonHandler.class files. The applet itself loads the background image and an audio file. To play the audio file, click on the Play button. The space music is played, using your sound board and speakers. When the music file ends, the sound ends. If you click on the Loop button, the music is played continuously. Clicking the Stop button causes the music to cease.

FIGURE 5.8. The audio.htm file, as displayed by HotJava.

The AudioPlayer class is fairly simple. It declares two field variables, music and background, which are used to hold the audio file and background image. The music variable is declared as type AudioClip, which is an interface defined in the java.applet package.

The AudioPlayer class contains three access methods: init(), stop(), and paint().

The init() method is invoked by the browser's runtime system when an applet is initially loaded. It performs any initialization required before the main part of the applet is executed. The stop() method is invoked when an applet is terminated as the result of an applet's Web page no longer being displayed by the browser. You never need to invoke init() or stop() directly. They are invoked by the runtime system.

The init() method of AudioPlayer begins by loading the audio and image files. The getCodeBase() method returns the URL of the directory where the applet file is located. The getAudioClip() method of the Applet class loads an audio file that is referenced by this URL and the spacemusic.au file name. The space.gif file is loaded in a similar manner.

After the audio and image files are loaded, the layout of the applet is set to a BorderLayout object. You'll learn about layouts in the next chapter. A Panel object is created and assigned to the buttons variable. The Play, Stop, and Loop buttons are created and added to the buttons panel. ButtonHandler objects are used to handle the events associated with these buttons. The buttons panel is then added to the bottom of the applet display area.

When the applet is no longer being displayed by the browser, the stop() method of the AudioPlayer class invokes the stop() method of the AudioClip interface to stop the music.

The paint() method draws the space.gif image assigned to the background variable on the Graphics context of the applet's display area.

The actionPerformed() method of the ButtonHandler inner class handles the three prominent events associated with the applet. These events are the clicking of the Play, Stop, and Loop buttons. When the Play button is clicked, the play() method of the AudioClip interface is invoked to play the audio clip. When the Stop button is clicked, the stop() method of the AudioClip interface is invoked to stop the music. Finally, when the Loop button is clicked, the loop() method of the AudioClip interface is invoked to cause the music to be played in a never-ending loop.

A Word About JavaBeans

As you learned in Chapter 4, "Overview of JDK 1.2 Programming," JavaBeans are software components that are designed for maximum reuse. They support the software component assembly model pioneered by Microsoft's Visual Basic and Borland's Delphi. For most people, they are the simplest way to create applets. Using a visual design tool, you just drag and drop beans into your applet. After that, all you need to do is to adjust the beans' properties to your liking and specify how the beans are to interact with each other.

However, the power of JavaBeans goes beyond rapid applet development. JavaSoft has developed the JavaBeans Bridge for ActiveX 1.0, which allows beans to interoperate with ActiveX. This means that you can use JavaBeans as ActiveX components in a number of Windows applications, including Microsoft Office, Visual Basic, and even Internet Explorer. Part VII of this book is dedicated to JavaBeans. You'll learn to develop your own beans, use them in applets, and work with bridges.

Java Plug-In

One of the biggest problems facing applet developers is maintaining backward compatibility with older browsers, such as Navigator 3.0 and Internet Explorer 3.0, that don't support JDK 1.1, let alone JDK 1.2. In order to provide applets that work with most of the installed browser base, applet developers were forced into a "least common denominator" approach. This approach generally results in applets that do not exceed the capabilities of JDK 1.02. JavaSoft developed Java Plug-In as a solution to this problem. Java Plug-In, formerly known as Activator, allows users to use various versions of Sun's Java Runtime Environment with their browser instead of the Java Virtual Machine provided by the browser vendor. This frees users of Internet Explorer from having to use Microsoft's broken JVM, and allows users of older Netscape browsers to conveniently upgrade to JDK 1.1 and JDK 1.2 runtime environments. Java Plug-In works with Navigator 3.0 or later and Internet Explorer 3.02 or later. Java Plug-In acts as an ActiveX control when used with Internet Explorer and as a browser plug-in when used with Navigator.

Summary

This chapter introduced the classes of the java.applet package and explained how applets are integrated within Web documents. It included a short introduction to HTML and explained how to use the HTML <APPLET> tag. It described how applets use window components and identified the major phases in an applet's life cycle. Applet multimedia capabilities, JavaBeans, and Activator were also introduced. Chapter 6, "GUI Building," shows how to build a graphical user interface for your applets.


Contents

© Copyright 1998, Macmillan Computer Publishing. All rights reserved.