Java Applets: Passing Parameter

Like command line arguments, parameters can be passed to applets. Applets can access those parameters and customize their tasks. This helps applets to function differently in different situations without recompiling the source code.

Parameters are passed to the applet using the <param> child tag of the <appiet> tag. Each <param> tag, as its name implies, passes one parameter to the surrounding applet. It has two attributes, name and value. They indicate the name and value of the parameter to be passed respectively. Consider the following parameter specification:

<applet code=”ParamDemo” width=”200” height=”60”>

<param name=”fontColor” value=”FF0000″>

<param name=”bgColor” value=”EEEEEE”>


It means that a ParamDemo applet is to be instantiated with two parameters fontcolor and bgCoior, whose values are ffoooo and eeeeee, respectively.

1. Retrieving Parameter

Parameters are retrieved from an applet using the getParameter() method. This methods takes the name of the parameter as an argument and returns the value of the parameter as a String. The prototype declaration of this method is as follows:

public java.lang.String getParameter(java.lang.String);

The following code shows how to retrieve the parameters using the getParameter () method. The retrieved values are then used to set the background and foreground color of the applet.


import java.awt.*;

import java.applet.*;

public class ParamDemo extends Applet {

String fontColor, bgColor; public void init() {

fontColor = getParameter(“fontColor”);

bgColor = getParameter(“bgColor”);


public void paint(Graphics g) {

setBackground(color(bgColor)); g.setColor(color(fontColor));

g.drawString(”Font Color :” + fontColor, 20, 20);

g.drawString(”Background color:” + bgColor, 20, 40);


public Color color(String color) {

int c = Integer.parseInt(color, 16);

int red = c / (256 * 256);

int green = (c / 256) % 256; int blue = c % 256;

return new Color(red, green, blue);



Note that the method getParameter() always returns the value of the specified parameter as a string. It is typically converted to the desired type. For example, in the ParamDemo applet, the value of the fontColor and bgColor parameters is a hexadecimal RGB value. To get the actual color from it, we have first converted it into an integer value using the Integer.parseInt() method. Then, we have extracted red, green, and blue components and finally created a color with these components.

The following code results in the output as shown in Figure 16.15:

<applet code=”ParamDemo” width=”200″ height=”60″>

<param name=”fontColor” value=”FFFFFF”>

<param name=”bgColor” value=”AAAAAA”>


Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *