Bookmark and Share

Applet Parameters

See the example applet in action in the demo or view the source code.

The PARAM tag may be used within an opening an closing APPLET (or OBJECT) tag pair to specify input data for an applet.

Any number of parameters can be added to define a set of name-value pairs which are then available to the applet. They can be used to allow the page designer to specify different colors, fonts, URLs or other data to be used by the applet.

<applet code="MyApplet.class" width="300" height="100">
  <param name="background-color" value="#ffffff">
  <param name="foreground-color" value="#000000">

Or, using the OBJECT tag:

<object codetype="application/java" classid="java:MyApplet.class"
        width="300" height="100">
  <param name="background-color" value="#ffffff" />
  <param name="foreground-color" value="#000000" />

The example applet simply displays a line of text. Different foreground and background colors to be set via parameters.

Accessing Parameters

Parameter data can be accessed within the applet init() method using getParameter(). It takes one argument, the name of the parameter which should match the NAME attribute of the PARAM tag, and returns the VALUE attribute as a string.

  public void init() {

    String s;

    s = getParameter("foreground-color");
    if (s != null)
      fgColorStr = s;

    s = getParameter("background-color");
    if (s != null)
      bgColorStr = s;


Note that the parameter names are case-insensitive, so "foreground-color" or "Foreground-Color" or even "FoReGrOuNd-CoLoR" can be used in either the PARAM tag or the method call.

Using Parameter Values

Since getParameter() returns a String object, you may need to convert it to a different data type before it can be used. For example,

    s = getParameter("url");
    if (s != null)
      URL url = new URL(getDocumentBase(), s);
    s = getParameter("counter");
    if (s != null)
      int i = Integer.parseInt(s);

The example applet includes a function to convert a string in standard HTML hex color format (e.g., "#ffcc33") to a valid Java color value.

  private Color parseColorStr(String s) {

      int r, g, b;

      // Convert a string in the standard HTML "#RRBBGG" format to a valid
      // color value, if possible.

      if (s.length() == 7 && s.charAt(0) == '#') {
        try {
          r = Integer.parseInt(s.substring(1,3),16);
          g = Integer.parseInt(s.substring(3,5),16);
          b = Integer.parseInt(s.substring(5,7),16);
          return(new Color(r, g, b));
        catch (Exception e) {}

      // Otherwise, default to black.


When coding an applet to accept parameters, keep in mind that the user may forget to add a particular PARAM tag, or use the wrong name or specify an invalid value. You should be sure to provide default values and perform validation to prevent bad parameters from causing runtime errors.