Appendix . Bonus Chapter: Writing Java Applets

The first exposure of many people to the Java programming language is in the form of applets, small and secure Java programs that run as part of a web page.

Though most programs that run on web pages are implemented today with Macromedia Flash, which loads faster in web browsers, Java continues to be a popular alternative for web-delivered interactive programs.

In this bonus chapter, you will learn how to create these web-based Java programs as you explore the following topics:

  • How to create a simple applet and present it on a web page

  • How to send information from a web page to an applet

  • How to store an applet in a Java archive so that it can be downloaded more quickly by web browsers

  • How to create applets run by the Java Plug-in, a virtual machine that improves a web browser’s Java support

How Applets and Applications Are Different

The difference between Java applets and applications lies in how they are run.

Applications are usually run by loading the application’s main class file with a Java interpreter, such as the java tool in the JDK.

Applets, on the other hand, are run on any browser that can support Java, such as Mozilla Firefox and Microsoft Internet Explorer. Applets also can be tested by using the JDK’s appletviewer tool.

For an applet to run, it must be included on a web page using HTML markup tags. When a user with a Java-capable browser loads a web page that includes an applet, the browser downloads the applet from a web server and runs it on the web user’s own system using a Java interpreter.

Though browsers once used built-in Java interpreters to run applets, the programs are executed today with the Java Plug-in, an interpreter offered as a browser add-on for each of the popular browsers.

Like an application, a Java applet includes a class file and any other helper classes that are needed to run the program. The Java class library is included automatically.

Applet Security Restrictions

Because Java applets are run on a web user’s system when loaded by a browser, they are subject to stringent security restrictions:

  • They cannot read or write files on the user’s file system.

  • They cannot communicate with a website other than the one that served the applet’s page.

  • They cannot load or run programs stored on the user’s system, such as executable programs and shared libraries.

Java applications have none of these restrictions. They can take full advantage of Java’s capabilities.

These restrictive security rules apply to all applets run by the Java Plug-in or built-in interpreter in an older browser. There is one way to get around this with the plug-in—an applet that has been digitally signed to verify the identity of the author can be granted the same access as Java applications. If a web user accepts a signed applet’s security certificate, the applet can run without restriction.

Caution

Although Java’s security model makes it difficult for a malicious applet to do harm to a user’s system, it will never be 100% secure. Search Google or another web search engine for “hostile applets”, and you’ll find discussion of security issues in different versions of Java and how they have been addressed.

Choosing a Java Version

To provide a way for applet programmers to use current versions of Java, Sun offers the Java Plug-in, which must be downloaded and installed by browser users unless it was included with their operating system.

This situation is a common source of errors for Java applet programmers. If you write a Java 6 applet and run it on an older browser without the plug-in, you will get security errors, class-not-found errors, and other problems that prevent the applet from running.

Creating Applets

Applets differ significantly from applications, most notably by lacking a main() method that automatically is called to begin execution of the program. Instead, several methods are called at different points in the execution of an applet.

Applets are subclasses of the JApplet class in the javax.swing package and are graphical user interface components similar to frames. They can contain other components and have layout managers applied to them.

By inheriting from JApplet, an applet runs as part of a web browser and can respond to events such as the browser page being reloaded. The applet also can take input from users.

All applets are created by subclassing JApplet:

public class AppletName extends javax.swing.JApplet {
    // applet code here
}

Applets must be declared public.

When a Java-equipped browser finds a Java applet on a web page, the applet’s class is loaded along with any other helper classes used by the applet. The browser automatically creates an instance of the applet’s class and calls methods of the JApplet class when specific events take place.

Each applet on a page will be its own applet object, even if they belong to the same class.

Applet Methods

Applets have methods called when specific things occur as the applet runs.

For instance, the paint() method is called when the applet window needs to be displayed or redisplayed.

The paint() method is similar to the paintComponent() method you worked with on Day 13, “Using Color, Fonts, and Graphics.” For text and graphics to be displayed on the applet window, the paint() method must be overridden with behavior to display something.

The following sections describe events that happen as an applet runs: initialize, start, stop, destroy, and paint. Some occur once only while others like paint occur as often as needed.

Initialization Method

Initialization occurs the first time an applet is loaded. It can be used to create objects the applet needs, load graphics or fonts, and the like.

To provide behavior for the initialization of an applet, you override the init() method in the following manner:

public void init() {
    // code here
}

One useful thing to do when initializing an applet is to set the color of its background window using a Color object, as in the following example:

Color avocado = new Color(102, 153, 102);
setBackground(avocado)

The preceding statements color the applet window avocado green when placed in an init() method.

Start Method

An applet is started after it is initialized and when the applet is restarted after being stopped. Starting can occur several times during an applet’s life cycle, but initialization happens only once.

An applet restarts when a web user returns to a page containing the applet. If a user clicks the Back button to return to the applet’s page, it starts again.

To provide starting behavior, override the start() method as follows:

public void start() {
    // code here
}

Functionality that you put in the start() method might include starting a thread to control the applet and calling methods of other objects that it uses.

Stop Method

An applet stops when the user leaves a web page that contains a running applet or when the stop() method is called.

By default, any threads an applet has started continue running even after a user leaves the applet’s page. By overriding stop(), you can suspend execution of these threads and restart them if the applet is viewed again. A stop() method takes this form:

public void stop() {
    // code here
}

Destroy Method

Destruction is the opposite of initialization. An applet’s destroy() method enables it to clean up after itself before it is freed from memory or the browser exits.

You can use this method to kill any running threads or to release any other running objects. Generally, you won’t want to override destroy() unless you have specific resources that need to be released, such as threads that the applet has created. To provide cleanup behavior for your applet, override the destroy() method as follows:

public void destroy() {
    // code here
}

Because Java’s automatic garbage collection handles the removal of objects when they’re no longer needed, there’s normally no need to use the destroy() method in an applet.

Paint Method

Painting is how an applet displays text and graphics in its window.

The paint() method is called automatically by the environment that contains the applet—normally a web browser—whenever the applet window must be redrawn. It can occur hundreds of times: once at initialization, again if the browser window is brought out from behind another window or moved to a different position, and so on.

You must override the paint() method of your JApplet subclass to display anything.

The method takes the following form:

public void paint(Graphics screen) {
    Graphics2D screen2D = (Graphics2D)screen;
    // code here
}

Unlike other applet methods, paint() takes an argument: a Graphics object that represents the area in which the applet window is displayed.

As in Day 13 with the paintComponent() method, a Graphics2D object is cast from this Graphics object and used for all text and graphics drawn in the applet window using Java2D.

The Graphics and Graphics2D classes are part of the java.awt package.

There are times in an applet when you do something that requires the window to be repainted. For example, if you change the applet’s background color, it won’t be shown until the applet window is redrawn.

To request that the window be redrawn in an applet, call the applet’s repaint() method without any arguments:

repaint();

Writing an Applet

Applets often present graphical information that updates dynamically as the program runs, a capability that can’t be achieved using normal web page markup.

The first project during this bonus chapter is the Watch applet, which displays the current date and time and updates the information roughly once a second.

This applet uses objects of several classes:

  • GregorianCalendar—A class in the java.util package that represents date/time values in the Gregorian calendar system, which is in use throughout the Western world

  • Font—A java.awt class that represents the size, style, and family of a display font

  • Rectangle2D.Float—A polygon class from the java.awt.geom package described in Day 13

  • Color and Graphics2D—Two java.awt classes described in the previous section

Listing 1 shows the source code for the applet.

Example 1. The Full Text of Watch.java

1: import java.awt.*;
2: import java.awt.geom.*;
3: import java.util.*;
4: import javax.swing.*;
5:
6: public class Watch extends JApplet {
7:     private Color butterscotch = new Color(255, 204, 102);
8:     Rectangle2D.Float background;
9:     Graphics2D screen2D;
10:
11:    public void init() {
12:        setBackground(Color.black);
13:    }
14:
15:    public void paint(Graphics screen) {
16:        super.paint(screen);
17:        Graphics2D screen2D = (Graphics2D)screen;
18:        Font type = new Font("Monospaced", Font.BOLD, 20);
19:        screen2D.setFont(type);
20:        screen2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
21:            RenderingHints.value_ANTIALIAS_ON);
22:        if (background == null) {
23:            // set up the background rectangle
24:            background = new Rectangle2D.Float(
25:                0F, 0F, (float)getSize().width, (float)getSize().height
26:            );
27:        }
28:        screen2D.fill(background);
29:        GregorianCalendar day = new GregorianCalendar();
30:        String time = day.getTime().toString();
31:        screen2D.setColor(butterscotch);
32:        screen2D.drawString(time, 5, 25);
33:        try {
34:            Thread.sleep(1000);
35:        } catch (InterruptedException e) {
36:            // do nothing
37:        }
38:        repaint();
39:    }
40: }

After you create this program, you can compile it, but you won’t be able to try it out yet. Applets must be run from a web page, which will be created in the next section.

The applet overrides the init() method to set the background color of the applet window to black.

The paint() method is where this applet’s real work occurs. The Graphics object passed into the paint() method holds the graphics environment, which keeps track of the current attributes of the drawing surface. The object can track details such as the font and color currently in use for any drawing operation, for example.

The method begins with a call to the paint(Graphics) method of the applet’s superclass, which ensures that the drawing surface is ready for use. In line 17, casting creates a Graphics2D object that contains the graphics environment suitable for Java2D graphics.

Lines 18–21 set up the font for this graphics state. The Font object is held in the type instance variable and set up as a bold, monospaced, 20-point font. The call to setFont() establishes this font as the one that will be used for subsequent drawing operations. Lines 20–21 improve the appearance of fonts and graphics by turning on antialiasing, a rendering technique that presents smoother edges.

Lines 22–27 ensure that the applet’s background, a black rectangle that fills the entire window, is set up properly. A Rectangle2D.Float object holds the rectangle, which is drawn by calling the Screen2D’s fill() method with the polygon as the argument:

screen2D.fill(background);

Lines 29–30 create a new GregorianCalendar object that holds the current date and time. The getTime() method of this object returns the date and time as a Date object, another class of the java.util package. Calling toString() on this object returns the date and time as a string you can display.

Lines 31–32 set the color using a Color object called butterscotch and then display the string time using this color.

Lines 33–37 use a class method of the Thread class to make the program do nothing for 1,000 milliseconds (one second). Because the sleep() method generates an InterruptedException error if anything occurs that should interrupt this delay, the call to sleep() must be enclosed in a try-catch block.

The paint() method ends with a call to repaint(), a request that the applet window be redrawn.

Caution

Calling repaint() within an applet’s paint() method is not the ideal way to handle animation; it’s suitable here because the applet is a simple one. A better technique is to use threads and devote a thread to the task of animation.

Including an Applet on a Web Page

After you create the class or classes that compose your applet and compile them into class files, you must create a web page on which to place the applet.

Applets are placed on a page by using applet, an HTML markup tag. Numerous web page development tools, such as Microsoft FrontPage 2003 and Macromedia Dreamweaver, also can be used to add applets to a page without using HTML.

The applet tag places an applet on a web page and controls how it looks in relation to other parts of the page.

A browser’s Java interpreter uses the information contained in the tag to find and execute the applet’s main class file.

Note

The following section assumes that you have at least a passing understanding of HTML or know how to use a web development tool to create web pages. If you need help in this area, one of the coauthors of this book, Laura Lemay, has written Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day with Rafe Colburn (ISBN 0-672-32886-0).

The Applet Tag

In its simplest form, the applet tag uses code, width, and height attributes to create a rectangle of the appropriate size and then loads and runs the applet in that space. The tag also includes several other attributes that can help you better integrate an applet into a web page’s overall design.

Note

The attributes available for the applet tag are almost identical to those for the IMG tag, which is used to display graphics on a web page.

Listing 2 contains the HTML markup for a web page that includes the Watch applet.

Example 2. The Full Text of Watch.html

1: <html>
2:   <head>
3:     <title>Watch Applet</title>
4:   </head>
5:   <body>
6:     <applet code="Watch.class" height="50" width="345">
7:     This program requires a Java-enabled browser.
8:     </applet>
9:   </body>
10: </html>

HTML tags are not case sensitive, so <applet> is the same as <APPLET>.

In Listing 2, the applet tag is contained in lines 6–8 and includes three attributes:

  • code—The name of the applet’s main class file

  • width—The width of the applet window on the web page

  • height—The height of the applet window

The class file indicated by the code attribute must be in the same folder as the web page containing the applet unless you use a codebase attribute to specify a different folder. You will learn how to do that later in this chapter.

The width and height attributes are required because the web browser needs to know how much space to devote to the applet on the page.

The text in line 7 of Listing 2 only will be displayed on a web browser that doesn’t support Java programs either because it lacks a Java interpreter or because the user has set the browser to ignore Java applets.

Text, graphics, and other web page elements can be included between the opening <applet> tag and the closing </applet> tag. If you don’t specify anything between the tags, browsers that don’t support Java display nothing in place of the applet.

Tip

The Java Plug-in can be downloaded and installed from the Java website at the address http://www.java.com. For the courtesy of people who view your web page without a Java-enabled browser, you can include a link to this site within the applet tag using this HTML markup:

This applet requires the <a href="http://www.java.com">Java Plug-in</a>.

Other Attributes

The applet tag supports additional attributes that can be used to customize the presentation of the applet.

The align attribute defines how the applet will be laid out on a web page in relation to other parts of the page. This attribute can have several different values. The most useful are “left” to present the applet on the left of adjacent text and graphics, “right” on the right, and “top” to align it with the topmost edge of adjacent items.

If you are using a web development tool that enables you to place Java applets on a page, you should be able to set the align attribute by choosing “left”, “right”, or one of the other values from within the program.

The hspace and vspace attributes set the amount of space, in pixels, between an applet and its surrounding text. hspace controls the horizontal space to the left and right of the applet, and vspace controls the vertical space above and below the applet. For example, here’s the HTML markup for an applet with vertical space of 50 and horizontal space of 10:

<applet code="ShowSmiley.class" width="45" height="42" align="left"
vspace="50" hspace="10">
    This applet requires Java.
</applet>

The code and codebase attributes indicate where the applet’s main class file and other files can be found.

code indicates the filename of the applet’s main class file. If code is used without an accompanying codebase attribute, the class file will be loaded from the same folder as the web page containing the applet.

You must specify the .class file extension with the code attribute. The following example loads an applet called Bix.class from the same folder as the web page:

<applet code="Bix.class" height="40" width="400">
</applet>

The codebase attribute indicates the folder where the applet’s class is stored. The following markup loads a class called Bix.class from a folder called Torshire:

<applet code="Bix.class" codebase="Torshire"
    height="40" width="400">
</applet>

Loading an Applet

After you have an applet’s class file and a web page that includes the applet, you can run the applet by loading the page with a web browser.

Open the Watch.html page created from Listing 2 in a web browser. One of three things may happen:

  • If the browser is equipped with the Java Plug-in, the applet will be loaded and will begin running.

  • If the browser does not offer any Java support, the following text will be displayed in place of the applet: “This program requires a Java-enabled browser.”

  • If the browser is not equipped with the Java Plug-in, but it does have its own builtin Java interpreter, the applet will not be loaded. An empty gray box will be displayed in its place.

If you installed the JDK, it’s likely you saw the applet running. The Java Plug-in can be installed along with the JDK and configured to replace the built-in Java interpreter in Internet Explorer and other web browsers.

Tip

If you are using the JDK, you also can use the appletviewer tool to view applets. Unlike a browser, appletviewer displays only the applets included on a web page. It does not display the web page itself.

Figure 1 shows the Watch.html page loaded with a copy of Mozilla Firefox 2.0 that has been equipped with the Java Plug-in.

Running an applet on a web page with the Java Plug-in.

Figure 1. Running an applet on a web page with the Java Plug-in.

Try to load this web page with each of the browsers installed on your computer. To try it with the JDK’s appletviewer, use the following command:

appletviewer Watch.html

If you can’t get the applet to load in a web browser, but you can load it with the JDK’s appletviewer tool, the most likely reason is because the browser isn’t equipped with the Java Plug-in.

This is a circumstance that will be faced by some of the people using your applet. They must download and install the Java Plug-in before they can view any Java applets in their browser.

Putting Applets on the Web

After you have an applet that works successfully when you test it on your computer, you can make the applet available on the Web.

If you know how to publish websites, you don’t have to learn any new skills to publish Java applets on a site.

Java applets are presented by a web server in the same way as web pages, graphics, and other files. You store the applet in a folder accessible to the web server—often the same folder that contains the web page that features the applet.

When you upload an applet to a web server, make sure to include each of the following files:

  • The web page where the applet is presented

  • The applet’s main class file

  • Any other class files required by the applet—with the exception of the Java class library

  • Any graphics and other files used by the applet

The most common ways to publish on the Web are by sending files through FTP (File Transfer Protocol) or web-design software that can publish sites.

Java Archives

The primary way to place a Java applet on a web page is to use the applet tag to indicate the applet’s class file. A Java-enabled browser downloads and runs the applet, loading any classes and any other files needed by the applet from the same web server.

Every file an applet needs requires a separate connection from a web browser to the server containing the file. Because a fair amount of time is needed just to make the connection, this can increase the amount of time it takes to download an applet and everything it needs to run.

The solution to this problem is to package the applet in a Java archive, which is also called a JAR file. A Java archive is a collection of Java classes and other files packaged into a single file.

When an archive is used, a web browser makes only one connection to download the applet and its associated files and can start running more quickly.

The JDK includes a tool called jar that can add and remove files in Java archives. JAR files can be compressed using the Zip format or packed without using compression.

Run jar without any arguments to see a list of options that can be used with the program. The following command packs all of a folder’s class and GIF graphics files into a single Java archive called Animate.jar:

jar cf Animate.jar *.class *.gif

The argument cf specifies two command-line options that can be used when running the jar program. The c option indicates that a Java archive file should be created, and f indicates that the name of the archive file will follow as one of the next arguments.

You also can add specific files to a Java archive with a command, such as

jar cf AudioLoop.jar AudioLoop.class beep.au loop.au

This creates an AudioLoop.jar archive containing three files: AudioLoop.class,

loop.au, and beep.au.

In an applet tag, the archive attribute shows where the archive can be found, as in the following example:

<applet code="AudioLoop.class" archive="AudioLoop.jar"
width="45" height="42">
</applet>

This tag specifies that an archive called AudioLoop.jar contains files used by the applet. Browsers and browsing tools that support JAR files will look inside the archive for files that are needed as the applet runs.

Caution

Although a Java archive can contain class files, the archive attribute does not remove the need for the code attribute. A browser still needs to know the name of the applet’s main class file to load it.

Passing Parameters to Applets

Java applications support the use of command-line arguments, which are stored in a String array when the main() method is called to begin execution of the class.

Applets offer a similar feature: They can read parameters that are set up with the HTML tag param, which has name and value attributes.

In the web page that contains the applet, one or more parameters can be specified with this tag. Each one must be placed within the opening and closing applet tags, as in the following example:

<applet code="QueenMab.class" width="100" height="100">
    <param name="font" value="TimesRoman">
    <param name="size" value="24">
    This applet requires <a href="http://www.java.com">Java</a>.
</applet>

This example defines two parameters to the QueenMab applet: font with a value of “TimesRoman” and size with a value of “24”.

Parameters are passed to an applet when it is loaded. In the init() method for your applet, you can retrieve a parameter by calling the getParameter(String) method with its name as the only argument. This method returns a string containing the value of that parameter or null if no parameter of that name exists.

For example, the following statement retrieves the value of the font parameter from a web page:

String fontName = getParameter("font");

Parameter names are case sensitive, so you must capitalize them exactly as they appear in an applet’s param tag.

Listing 3 contains a modified version of the Watch applet that enables the background color to be specified as a parameter.

Example 3. The Full Text of NewWatch.java

1: import java.awt.*;
2: import java.awt.geom.*;
3: import java.util.*;
4: import javax.swing.*;
5:
6: public class NewWatch extends JApplet {
7:     private Color butterscotch = new Color(255, 204, 102);
8:     Rectangle2D.Float background;
9:     Graphics2D screen2D;
10:    Color primary;
11:
12:    public void init() {
13:        String parameter = getParameter("primary");
14:        if (parameter != null) {
15:            try {
16:                primary = Color.decode(parameter);
17:            } catch (NumberFormatException e) {
18:                showStatus("Bad parameter " + parameter);
19:                primary = Color.black;
20:            }
21:        }
22:        setBackground(primary);
23:    }
24:
25:    public void paint(Graphics screen) {
26:        super.paint(screen);
27:        Graphics2D screen2D = (Graphics2D)screen;
28:        Font type = new Font("Monospaced", Font.BOLD, 20);
29:        screen2D.setFont(type);
30:        screen2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
31:            RenderingHints.VALUE_ANTIALIAS_ON);
32:        if (background == null) {
33:            // set up the background rectangle
34:            background = new Rectangle2D.Float(
35:                0F, 0F, (float)getSize().width, (float)getSize().height
36:            );
37:        }
38:        screen2D.setColor(primary);
39:        screen2D.fill(background);
40:        GregorianCalendar day = new GregorianCalendar();
41:        String time = day.getTime().toString();
42:        screen2D.setColor(butterscotch);
43:        screen2D.drawString(time, 5, 25);
44:        try {
45:            Thread.sleep(1000);
46:        } catch (InterruptedException e) {
47:            // do nothing
48:        }
49:        repaint();
50:    }
51: }

The init() method in lines 12–23 has been rewritten to work with a parameter named “primary”, which is read into the primary object in line 13:

String parameter = getParameter("primary");

The parameter is specified as a color value represented by a hexadecimal string—a pound character (“#”) followed by three hexadecimal numbers that represent the amount of red, green, and blue values of a color. Black is #000000, red is #ff0000, green is #00ff00, blue is #0000ff, white is #ffff, and so on. If you are familiar with HTML, you have probably used hexadecimal strings before.

Caution

The getParameter() method returns null when the parameter’s missing from the page or has a mismatched name. Make sure that the parameter’s name in the web page matches the string in getParameter(). Also make sure that your param tags are placed inside the opening and closing applet tags.

The Color class has a decode(String) class method that creates a Color object from a hexadecimal string. This is called in line 16; the try-catch block handles the NumberFormatException error that occurs if in does not contain a valid hexadecimal string.

If no “primary” parameter is specified, the default is black.

Line 22 sets the applet window’s background to the color represented by the primary object.

In the applet’s paint() method, the color is changed to the background color, and a rectangle is drawn to fill the entire window:

screen2D.setColor(primary);
screen2D.fill(background);

To try this program, create the HTML document in Listing 4.

Example 4. The Full Text of NewWatch.html

1: <html>
2:    <head>
3:      <title>Watch Applet</title>
4:    </head>
5:    <body bgcolor="#996633">
6:      <applet code="NewWatch.class" height="50" width="345">
7:        <param name="primary" value="#996633">
8:        This program requires <a href="http://www.java.com">Java</a>.
9:      </applet>
10:    </body>
11: </html>

On this page, the primary parameter is specified on line 7 with the value “#996633”. This string value is the hexadecimal color value for a shade of brown. In Listing 4, line 5 of the applet sets the web page’s background color using the same hexadecimal color value.

Loading this web page with a browser produces the result shown in Figure 2.

Viewing the NewWatch.html page in a browser.

Figure 2. Viewing the NewWatch.html page in a browser.

Because the applet window and web page have the same background color, the edges of the applet are not visible in Figure 2.

Running Applets with Java Web Start

The Java Web Start technique covered in Day 14, “Developing Swing Applications,” also can be used to run applets.

Applets loaded by Web Start execute differently than they do in a browser. The applet uses the same default security as an application, asking users for permission to undertake some tasks, and it is not displayed in a web page. The applet runs in its own window, making it appear to be an application.

To run an applet with Web Start, use the applet-desc element instead of the application-desc element.

The applet-desc element, which must be contained within the resources element, has five attributes:

  • name—The name of the applet.

  • main-class—The name of the applet’s main class, which will be executed when the applet is run.

  • width—The width of the applet window.

  • height—The height of the applet window.

  • documentBase—The base URL of the document. When the applet is run by a browser, the document base is a folder that holds the page containing the applet. Java Web Start does not run applets inside a page, so there is no way to automatically determine the document base. Because some applets call getDocumentBase() to use this URL, it must be explicitly specified as an attribute.

If an applet is run with parameters, these are specified with the param element, which is contained within applet-desc. This takes the same form in a JNLP file that it does on an HTML page:

<param name="somename" value="somevalue">

The final project is the conversion of the NewWatch applet to use Java Web Start.

To get ready for the project, copy the NewWatch.class file to a folder and add it to a new JAR archive using the following command:

jar -cf NewWatch NewWatch.class

A JAR archive called NewWatch.jar is created. This file is used by Java Web Start to run the applet. To accomplish this, enter the text of Listing 5, saving the JNLP file as NewWatch.jnlp.

Example 5. The Full Text of NewWatch.jnlp

1: <?xml version="1.0" encoding="utf-8"?>
2: <!— JNLP File for the NewWatch Applet —>
3: <jnlp
4:   codebase="http://www.cadenhead.org/book/java-21-days/java"
5:   href="NewWatch.jnlp">
6:   <information>
7:     <title>New Watch Applet</title>
8:     <vendor>Rogers Cadenhead</vendor>
9:     <homepage href="http://www.java21days.com"/>
10:    <description kind="one-line">An applet that displays
11: the current time.</description>
12:    <offline-allowed/>
13:  </information>
14:  <resources>
15:    <j2se version="1.2+"/>
16:    <jar href="NewWatch.jar"/>
17:  </resources>
18:  <applet-desc
19:    name="NewWatch applet"
20:    main-class="NewWatch"
21:    documentBase="http://www.cadenhead.org/book/java21days"
22:    width="345"
23:    height="50">
24:
25:    <param name="background" value="#996633">
26:  </applet-desc>
27: </jnlp>

The applet-desc element runs the NewWatch applet in a window 345 pixels wide and 50 pixels high. One parameter is specified using a param-name element in line 25: the background color to display underneath the current date and time.

Although applets are no longer the focus of Java development, they are still the element of Java technology that reaches the most people, appearing on thousands of websites.

Because they are executed and displayed within web pages, applets can use the graphics, user interface, and event structure provided by the web browser.

This capability provides the applet programmer with a lot of functionality without a lot of extra toil.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset