Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Configurable Applets in Java

In this java tutorial, you get a look at configurable applets, which enable the applets user to modify how an applet looks and acts, all without having to change a line of Java code.

In this java tutorial, you get a look at configurable applets, which enable the applets user to modify how an applet looks and acts, all without having to change a line of Java code.

If you have questions about java applets, check out this free tutorial about java applets.

Most of the applets you've written so far have onething in common. Outside of the starting size of the applet, none of yourapplets are configurable. That is, the user can't configure the applet to fithis needs. In many cases, it doesn't make sense to give the user configurableoptions. But, just as often, someone who wants to use your applet in his ownhome page will want to make minor changes without having to change andrecompile the source code. In fact, the user probably won't even have access tothe source 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 this article, you'll not only learn how to support applet parameters, but you'll also learn how to make those parameters user-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 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:

        

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 My first 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 1.

Listing1: Using a Parameter in an HTML Document.

Applet Test Page

Applet Test Page

code="TitleApplet.class"

width=250

height=150

name="TitleApplet">

     

As you can see, the tag is enclosed between the and 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.

The parameter is defined in the HTML document like this:

        

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 2 is an applet called ConfigApplet, which takes a single parameter. This parameter is the text string to display. Listing 3 is the HTML document that loads and runs the applet.

Listing 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);

      }

}

Line by line

- 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 3 - CONFIGAPPLET.htmL : HTML Document for ConfigApplet.

Applet Test Page

Applet Test Page

code="ConfigApplet.class"

width=250

height=150

name="ConfigApplet">

     

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 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 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 4 - CONFIGAPPLET2.htmL: HTML Document for ConfigApplet2.

Applet Test Page

Applet Test Page

code="ConfigApplet2.class"

width=350

height=200

name="ConfigApplet2">

     

     

     

     

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 5 is the Java source code for ConfigApplet2, which accomplishes all these tasks.

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 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);

      }

}

Line by line

- 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 6. You'd then completely change the way the text string is displayed in the applet, parameters can have a profound effect on the way an applet looks and acts.

Listing 6: New Parameters for ConfigApplet2.

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 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 8 is the HTML document used to load and run the applet.

Listing 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);

      }

}

Line by line

- 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 8 - CONFIGAPPLET3.htmL: The HTML Document for ConfigApplet3.

Applet Test Page

Applet Test Page

code="ConfigApplet3.class"

width=640

height=200

name="ConfigApplet3">

     

     

     

     

Conclusion

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 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 developer.



MrBool is a totally free website made for software developers. Our articles and courses are totally free with focus on useful techniques and best practices

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login