Processing An Unknown Number Of Parameters

Most of the time you have a fairly good idea of what parameters will and won't be passed to your applet. However some of the time there will be an undetermined number of parameters. For instance Sun's imagemap applet passes each "hot button" as a parameter. Different imagemaps have different numbers of hot buttons. Another applet might want to pass a series of URLs to different sounds to be played in sequence. Each URL could be passed as a separate parameter.

Or perhaps you want to write an applet that displays several lines of text. While it would be possible to cram all this information into one long string, that's not too friendly to authors who want to use your applet on their pages. It's much more sensible to give each line its own PARAM element. If this is the case, you should name the tags via some predictable and numeric scheme. For instance in the text example the following set of PARAM elements would be sensible:

<PARAM name="Line1" value="There once was a man from Japan">
<PARAM name="Line2" value="Whose poetry never would scan">
<PARAM name="Line3" value="When asked reasons why,">
<PARAM name="Line4" value="He replied, with a sigh:">
<PARAM name="Line5" value="I always try to get as many 
syllables into the last line as I can.">

The program below displays this limerick. Lines are accumulated into an array of strings called poem. A for loop fills the array with the different lines of poetry. There are 101 spaces in the array, but since you won't normally need that many, an if clause tests to see whether the attempt to get a parameter was successful by checking to see if the line is null. As soon as one fails, the loop is broken. Once the loop is finished numLines is decremented by one because the last line the loop tried to read wasn't there.

The paint() method loops through the poem array and prints each String on the screen, incrementing the y position by fifteen pixels each step so you don't draw one line on top of the other.


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 1, 2005