Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Handling Parameters in an Applet 243

<appletcode=”ScrollingHeadline”height=”50” width=”400”>
<paramname=”headline1”value=”Dewey defeats Truman”>
<paramname=”headline2”value=”Stix nix hix pix”>
<paramname=”headline3”value=”Man bites dog”>



This markup could be used with an applet that scrolls news headlines
across a web page. Because news changes all the time, the only way to
design a program like that is through the use of parameters.


Thenameattribute give a parameter a name and valueassigns it a value.


Receiving Parameters in the Applet


You access parameters in an applet by.calling the getParameter(String)
method of the applet—inherited from JApplet—with its name as the argu-
ment, as in this statement:


String display1 = getParameter(“headline1”);


The getParameter()method returns parameter values as strings, so they
must be converted to other types as needed. If you want to use a parame-
ter as an integer, you could use statements such as the following:


int speed;
String speedParam = getParameter(“speed”);
if (speedParam != null) {
speed = Integer.parseInt(speedParam);
}


This example sets the speedinteger variable by using the speedParam
string. When you try to retrieve a parameter with getParameter()that
was not included on a web page with the paramtag, it is sent as null,
which is the value of an empty string.


Handling Parameters in an Applet


The workshop for this hourtakes a person’s weight and displays it under
several different units. The applet takes two parameters: a weight in
pounds and the name of the person who weighs that amount. The weight
is used to figure out the person’s weight in ounces, kilograms, and metric
tons, which are all displayed.


Create a new empty Java file called WeightScale, enter the text of
Listing 17.3 into the file, and save the file.


CAUTION
TheInteger.parseInt(String)
method requires the use of
exceptions,a technique you
learn about during Hour 18,
“Handling Errors in a Program.”
Free download pdf