Chapter 26

Configurable Applets


CONTENTS

All of the applets you've written so far have one thing in common. Outside of the starting size of the applet, none of your applets are configurable. That is, the user can't configure the applet to fit his needs. In many cases, it doesn't make sense to give the user configurable options. But, just as often, someone who wants to use your applet in his own home page will want to make minor changes without having to change and recompile the source code. In fact, the user probably won't even have access to the source code. In this chapter, you get a look at configurable applets, which enable the applet's user to modify how an applet looks and acts, all without having to change a line of Java code.

Types of Users

Before you read further, it might be a good idea to define exactly what a user is. When it comes to applets, you could say that there are two kinds of users. The first kind is a net surfer who logs onto your home page and sees all the cool applets you've spent the last six months creating. Because this user is not installing your applets on his own Web pages-he's just a casual observer-he doesn't need access to the applet's parameters. In fact, if you want your Web pages to look right for different users, it just doesn't make sense to enable the surfer to configure an applet.

The other kind of user is the guy who found your applet on a server somewhere and wants to incorporate the applet into his own Web pages. Assuming that you've released your applet into the world for others to use, you want this type of user to find your applet to be as flexible as possible. However, you probably don't want to give this user your source code and expect him to make changes that require recompiling. Hey, he could end up trashing the applet completely, right?

So, to make it easy for this user to modify the applet's appearance and functionality, you must build in support for parameters. To use these parameters, the user only needs to add a few lines to the HTML document that loads and runs the applet. For example, you may have written an applet that displays an awesome title on your home page. Now, you want to release the applet so that other netfolks can use it in their Web pages. However, these folks are going to want to display their own titles. So, you make the title string a parameter.

In the sections that follow, you'll not only learn how to support applet parameters, but you'll also learn how to make those parameters idiot-proof.

Parameters and Applets

When you want to use an applet that supports parameters, you must add the parameters and their values to the HTML document that loads and runs the applet. You do this using the <PARAM> tag, which has two parts. The NAME part of the tag specifies the parameter's name, and the VALUE part specifies the parameter's value. For example, suppose you want to provide a title parameter for that title applet you read about in the previous section. The parameter tag might look like this:


<PARAM NAME=title VALUE="Big Al's Home Page">

Here, the name of the parameter is title. The applet will use this name to identify the parameter. The value of the title parameter in the above line is the text string Big Al's Home Page. The applet will retrieve this text string in order to display the title the user wants. A complete HTML document for the title applet might look something like Listing 26.1.


Listing 26.1  LST26_1.TXT: Using a Parameter in an HTML Document.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="TitleApplet.class"

    width=250

    height=150

    name="TitleApplet">

    <PARAM NAME=title VALUE="Big Al's Home Page">

</applet>


As you can see, the <PARAM> tag is enclosed between the <applet> and </applet> tags. that is, the parameters are part of the applet's HTML code.

How does your applet retrieve the parameter at run time? An excellent question, and one for which I fortunately have the answer. To retrieve a parameter, you call the applet's getParameter() method, like this:


String param = getParameter(name);

The getParameter() method takes a single argument, which is a string containing the name of the parameter for which you want the value. The method always returns a string to your applet. This string is, of course, the part of the PARAM tag that follows the VALUE=.

Example: Setting and Retrieving a Parameter's Value

Suppose that you've written an applet that displays a fancy greeting to the viewer. (How fancy the greeting is displayed depends upon the code you've written for the applet. Because how the applet actually displays this greeting is not important at this point, just pretend it does something really cool.) The parameter is defined in the HTML document like this:


<PARAM NAME=greeting VALUE="All Web Surfers Welcome!">

When the applet runs, it has to find out what greeting to display. So, in the applet's init() method is the following line:


String str = getParameter("greeting");

Now that the applet has the text stored in the str variable, it can manipulate and display it any way it needs to.

Example: Using a Parameter in an Applet

Now that you know how to create HTML documents that set parameters, as well as how to obtain those parameters from within your applet, you'd probably like a real parameterized applet with which you can experiment. Listing 26.2 is an applet called ConfigApplet, which takes a single parameter. This parameter is the text string to display. Listing 26.3 is the HTML document that loads and runs the applet. Notice the <PARAM> tag. When you run the applet with Appletviewer, you see the window shown in Figure 26.1.

Figure 26.1 : This applet's display string is given as a parameter.


Listing 26.2  ConfigApplet.java: An Applet with a Single Parameter.

import java.awt.*;

import java.applet.*;



public class ConfigApplet extends Applet

{

    String str;



    public void init()

    {

        str = getParameter("text");



        Font font = new Font("TimesRoman", Font.BOLD, 24);

        setFont(font);

    }



    public void paint(Graphics g)

    {

        g.drawString(str, 50, 50);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ConfigApplet class from Java's Applet class.
Declare the class's data field.
Override the init() method.
Retrieve the value of the text parameter.
Create and set the font for the applet.
Override the paint() method.
Display the given string.

Listing 26.3  CONFIGAPPLET.htmL: HTML Document for ConfigApplet.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="ConfigApplet.class"

    width=250

    height=150

    name="ConfigApplet">

    <PARAM NAME=text VALUE="Display Text">

</applet>


Once you get ConfigApplet compiled, try running the applet several times, each time changing the parameter in the HTML document to a new text string. This will give you a good example of how parameters work from the HTML document writer's point of view. Changing the value of the parameter in the HTML document is all you need to do to display a different text string. You don't have to change the applet's source code at all.

Multiple Parameters

When you're writing an application that others may use in their Web pages, it's important that you make the applet as flexible as possible. One way to do this is to use parameters for any applet value that the user might like to customize. Adding multiple parameters is just a matter of adding additional <PARAM> tags to the HTML document and then retrieving the values of the parameters in the applet. In the next example, you take a look at ConfigApplet2, which gives the user much more control over how the applet displays the text string.

Example: Using Multiple Parameters in an Applet

Suppose that you want to rewrite ConfigApplet so that the user can customize not just the text string the applet will display, but also the position of the text and the size of the font used to print the text. To do this, you need to create four parameters, one each for the text to display, the X position of the text, the Y position of the text, and the point size of the font. Listing 26.4 is an HTML document that loads and runs the ConfigApplet2 applet, which is a new version of ConfigApplet. Notice that the HTML document now specifies four parameters for the applet. You can specify as many parameters as you need for an applet.


Listing 26.4  CONFIGAPPLET2.htmL: HTML Document for ConfigApplet2.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="ConfigApplet2.class"

    width=350

    height=200

    name="ConfigApplet2">

    <PARAM NAME=text VALUE="Display Text">

    <PARAM NAME=typesize VALUE=72>

    <PARAM NAME=xpos VALUE=20>

0    <PARAM NAME=ypos VALUE=100>

</applet>


In the above HTML document, the user is specifying that he wants to display the text string Display Text in 72-point type and at position 20,100. The applet, of course, must call getParameter() to read these values into the applet. Moreover, the applet must call getParameter() once for each parameter. After retrieving the parameters, the applet must initialize itself such that it displays the text as requested. Listing 26.5 is the Java source code for ConfigApplet2, which accomplishes all these tasks. Figure 26.2 shows the applet running under Appletviewer, using the parameters given in the HTML document in Listing 25.4.

Figure 26.2 : This applet accepts four parameters that determine how the text is displayed.

NOTE
Because the getParameter() method always returns a string, you may have to convert some parameters before you can use them in your applet. For example, the ConfigApplet2 applet must convert its typesize, xpos, and ypos parameters from strings to integers.


Listing 26.5  ConfigApplet2.java: The ConfigApplet2 Applet.

import java.awt.*;

import java.applet.*;



public class ConfigApplet2 extends Applet

{

    String str;

    Point position;



    public void init()

    {

        String s;



        str = getParameter("text");



        s = getParameter("typesize");

        int typeSize = Integer.parseInt(s);



        s = getParameter("xpos");

        int xpos = Integer.parseInt(s);



        s = getParameter("ypos");

        int ypos = Integer.parseInt(s);



        position = new Point(xpos, ypos);



        Font font = new Font("TimesRoman", Font.BOLD, typeSize);

        setFont(font);

    }



    public void paint(Graphics g)

    {

        g.drawString(str, position.x, position.y);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ConfigApplet2 class from Java's Applet class.
Declare the class's data fields.
Override the init() method.
Declare a local variable.
Retrieve the value of the text parameter.
Retrieve and convert the typesize parameter.
Retrieve and convert the xpos parameter.
Retrieve and convert the ypos parameter.
Store the position in a Point object.
Create and set the font for the applet, using typesize.
Override the paint() method.
Display the given string.

Suppose you were to change the parameters in the HTML file to those shown in Listing 26.6. You'd then completely change the way the text string is displayed in the applet, as shown in Figure 26.3. As you can see, parameters can have a profound effect on the way an applet looks and acts.

Figure 26.3 : Here's ConfigApplet2 running with different parameters.


Listing 26.6  LST26_6.TXT: New Parameters for ConfigApplet2.

<PARAM NAME=text VALUE="New Text String">

<PARAM NAME=typesize VALUE=18>

<PARAM NAME=xpos VALUE=60>

<PARAM NAME=ypos VALUE=150>


Default Parameter Values

You might have noticed by now that there's a big problem with the ConfigApplet and ConfigApplet2 applets. Neither applet checks to ensure that the parameters it tries to retrieve exist. For example, what happens when the user forgets to include the text parameter?

Relying on other people to provide your applet with the data it needs is a dangerous practice. Your applet should always check the validity of values returned from the getParameter() method. At the very least, you should be sure that the returned value is not null, which is the value getParameter() returns when a particular parameter doesn't exist (that is, the user forget to define it in the HTML document or deliberately left it out assuming that the applet will automatically use a default value for the missing one).

To ensure that your applet is in a runnable state after retrieving parameters, you must always check the parameter's values and supply default values for those parameters that are missing or invalid. For example, to make sure that your applet has a text string to display, you might use lines like this:


str = getParameter("text");

if (str == null)

    str = "Default Text";

NOTE
If you decide to release your applets so other people can use them in their Web pages, be sure that you include a separate documentation file that describes the applet's parameters and shows how to use them.

Example: Using Default Parameters in an Applet

You can now extend the ConfigApplet2 so that it provides default values for each parameter. When you've done this, the applet can run without generating errors no matter what parameters the user chooses to include or ignore. Listing 26.7 is the new version, called ConfigApplet3.

Notice that although the program now checks for missing parameters, it doesn't limit the values to any ranges or otherwise check their validity. Because the text parameter will always be a string, there's really nothing you need to check for (except null). However, you may want to limit the font size or make sure that the display location is inside the applet's window. Listing 26.8 is the HTML document used to load and run the applet as it's displayed in Figure 26.4.

Figure 26.4 : This is ConfigApplet3 running under Appletviewer.


Listing 26.7  ConfigApplet3.java: This Applet Provides Default Values for All Parameters.

import java.awt.*;

import java.applet.*;



public class ConfigApplet3 extends Applet

{

    String str;

    Point position;



    public void init()

    {

        HandleTextParam();

        HandleTypeSizeParam();

        HandlePositionParam();

    }



    public void paint(Graphics g)

    {

        g.drawString(str, position.x, position.y);

    }



    protected void HandleTextParam()

    {

        str = getParameter("text");

        if (str == null)

            str = "Default Text";

    }



    protected void HandleTypeSizeParam()

    {

        String s = getParameter("typesize");

        if (s == null)

            s = "24";

        int typeSize = Integer.parseInt(s);



        Font font = new Font("TimesRoman", Font.BOLD, typeSize);

        setFont(font);

    }



    protected void HandlePositionParam()

    {

        String s = getParameter("xpos");

        if (s == null)

            s = "20";

        int xpos = Integer.parseInt(s);



        s = getParameter("ypos");

        if (s == null)

            s = "50";

        int ypos = Integer.parseInt(s);



        position = new Point(xpos, ypos);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ConfigApplet3 class from Java's Applet class.
Declare the class's data fields.
Override the init() method.
Call the methods that retrieve and validate the parameters.
Override the paint() method.
Display the given string.
Define the HandleTextParam() method.
Retrieve the text parameter.
If the parameter is null, set str to the default text.
Define the HandleTypeSizeParam() method.
Retrieve the typesize parameter.
If the parameter is null, set the parameter string to "24."
Convert the parameter string to an integer.
Create and set the font.
Define the HandlePositionParam() method.
Retrieve the xpos parameter.
if xpos is null, set the parameter string to "20."
Convert the parameter string to an integer.
Retrieve the ypos parameter.
if ypos is null, set the parameter string to "50."
Convert the parameter string to an integer.
Create the Point object with the position values.

Listing 26.8  CONFIGAPPLET3.htmL: The HTML Document for ConfigApplet3.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="ConfigApplet3.class"

    width=640

    height=200

    name="ConfigApplet3">

    <PARAM NAME=text VALUE="Hi there!">

    <PARAM NAME=typesize VALUE=144>

    <PARAM NAME=xpos VALUE=40>

    <PARAM NAME=ypos VALUE=140>

</applet>


Summary

By supporting parameters, your applets are more flexible, which makes it easier for other people to incorporate them into their Web-page designs. Even if you don't plan to release your applets, using parameters can make your applets more powerful and your own Web pages easier to fine tune. Using the <PARAM> tag is more sensible than having to reprogram and recompile an applet every time you want it to do something slightly different. Keep in mind, though, that all parameters must have default values built into the applet's source code. Otherwise, you could end up with an error-ridden applet, something that won't do much for your reputation as a Java guru.

Review Questions

  1. What kind of applet user is likely to appreciate parameterized applets?
  2. What are the two parts of the <PARAM> tag?
  3. How can your applet retrieve the value of a parameter?
  4. Where do you specify the values for an applet's parameters?
  5. Do you need to recompile an applet in order to take advantage of new parameters?
  6. How many parameters can you have in a single applet?
  7. Why do you need to convert the values of some parameters?
  8. Why is it important to supply default values for all parameters?

Review Exercises

  1. Write an applet that displays a rectangle on the screen. The rectangle's size should be specified using parameters.
  2. Write an applet that uses a parameter to display a red, green, or blue background.
  3. Modify ConfigApplet2 so that it not only checks for null parameters, but also checks for the parameters' validity. The type size should always be in the range of 10 to 72 points and the text should always be positioned so that it's never printed completely out of view. (You can find the solution to this exercise, called ConfigApplet4, in the CHAP26 folder of this book's CD-ROM.)