Java Reference
In-Depth Information
18.7 Passing Strings to Applets
You can pass string parameters from an HTML file to an applet.
Key
Point
In Section 9.7, Command-Line Arguments, you learned how to pass strings to Java applica-
tions from a command line. Strings are passed to the main method as an array of strings.
When the application starts, the main method can use these strings. There is no main
method in an applet, however, and applets are not run from the command line by the Java
interpreter.
How, then, can applets accept arguments? In this section, you will learn how to pass
strings to Java applets. To be passed to an applet, a parameter must be defined in the HTML
file and must be read by the applet when it is initialized. Parameters are defined using the
<param> tag. The <param> tag must be embedded in the <applet> tag. Its syntax is:
< param name = parametername value = stringvalue />
The <param> tag defines a parameter and its corresponding string value.
Note
No comma separates the parameter name from the parameter value in the HTML code.
The HTML parameter names are not case sensitive.
Suppose you want to write an applet to display a message. The message is passed as a
parameter. In addition, you want the message to be displayed at a specific location with x -
coordinate and y -coordinate, which are passed as two parameters. The parameters and their
values are listed in Table 18.1.
T ABLE 18.1 Parameter Names and Values for
the DisplayMessage Applet
Parameter Name
Parameter Value
"Welcome to Java"
MESSAGE
X
20
Y
30
The HTML source file is given in Listing 18.4.
L ISTING 18.4 DisplayMessage.html
<html>
<head>
<title> Passing Strings to Java Applets </title>
</head>
<body>
<p>This applet gets a message from the HTML
page and displays it.</p>
<applet
code = "DisplayMessage.class"
width = 200
height = 50
alt = "You must have a Java-enabled browser to view the applet"
>
<param name = MESSAGE value = "Welcome to Java" />
<param name = X value = 20 />
 
 
Search WWH ::




Custom Search