Sending Parameters to Applets

Java applets are never run from the command line, so you can't specify arguments the way you can with apps. Applets use a different way to receive information at the time the program is run. This configuration information is called parameters, and you can send parameters through the HTML page that runs the applet. You have to use a special HTML tag for parameters called param. To see how the Blanks app would be rewritten as an applet, open your word processor, enter the text of Listing 4.5, then save the file as

Listing 4.5. The Full Text of
 1: import java.awt.*;
 3: public class BlanksApplet extends javax.swing.JApplet {
 4: String parameter1;
 5: String parameter2;
 6: String parameter3;
 8: public void init() {
 9: parameter1 = getParameter("adjective1");
10: parameter2 = getParameter("adjective2");
11: parameter3 = getParameter("adjective3");
12: }
14: public void paint(Graphics screen) {
15: screen.drawString("The " + parameter1
16: + " " + parameter2 + " fox "
17: + "jumped over the "
18: + parameter3 + " dog.", 5, 50);
19: }
20: }

Save the file and then compile it. Using the JDK, you can accomplish this by typing the following at the command line:


Before you can try out this applet, you need to create a web page that displays the BlanksApplet applet after sending it three adjectives as parameters. Open your word processor and enter Listing 4.6, saving it as BlanksApplet.html.

Listing 4.6. The Full Text of BlanksApplet.html
1: <applet code="BlanksApplet.class" height=80 width=500>
2: <param value="lachrymose">
3: <param value="magenta">
4: <param value="codependent">
5: </applet>

Save the file when you're done, and load the page using Internet Explorer, the JDK's appletviewer, or another browser equipped with the Java plug-in. The page when loaded in your browser should resemble Screenshot. Change the values of the value attribute in Lines 2–4 of the BlanksApplet.html file, replacing "lachrymose", "magenta", and "codependent" with your own adjectives, then save the file and run the program again. Try this several times, and you'll see that your program is now flexible enough to handle any adjectives, no matter how well or how poorly they describe the strange relationship between the fox and the dog.

Screenshot The BlanksApplet program displayed with a web browser.

Java ScreenShot

You can use as many parameters as needed to customize the operation of an applet, as long as each has a different name attribute specified along with the param tag.