You are here

A Primer on Reuse - Reading Applet Parameters

Author(s): 
Mark Chung and Chris DiGiano

Your applet can read a parameter specified in the HTML simply by using the Applet.getParameter() method, which takes a String specifying the parameter name. It returns the value as a String if the parameter was specified, or null if not specified. Since you will want to handle the case in which the parameter is not specified by using a default value, you could add a convenience method to your applet class. It reads a parameter with the specified name and returns the value as a String, specifying a default value in case the parameter is not found:

 public String getParameter(String key, String def) {
     if (getParameter(key) != null)
         return getParameter(key);
     else
         return def;
 }


Here is an example of how to invoke this method to get the value of a parameter named "xlabel", providing a default value, and to pass the value to a setter method:

setXLabel(getParameter("xlabel", "X"));

The following method reads in a parameter as a float and specifies a default value in case the parameter is not found or there is a problem parsing the value as a float:
 

public float getFloatParameter(String key, float defaultValue) {
    try {
        if (getParameter(key) != null)
            return Float.valueOf(getParameter(key)).floatValue();
    }
    catch (NumberFormatException nfe) {
        nfe.printStackTrace();
        // fall through and return default value
    }
    return defaultValue;
}

Similar methods could be written to get parameters of different types.

Here is an example of how to invoke this method to get the value of a parameter named "xmin", providing a default float value:

setXMin(getFloatParameter("xmin", -10.0F));

The Applet API also provides the method getParameterInfo(), which you can override to provide information so that a web browser could present an interface to change the parameters. Currently, no web browsers use this information, but you may choose to implement this for completeness. For more information, see the section Giving Information about Parameters in the Writing Applets trail of the Java Tutorial.

Mark Chung and Chris DiGiano, "A Primer on Reuse - Reading Applet Parameters," Convergence (December 2004)