Passing Parameters to Applets

The area between the opening and closing APPLET tag is also used to pass parameters to applets. This is done through the use of the PARAM HTML tag and the getParameter method of the java.applet.Applet class.

To demonstrate this we’ll convert HelloWorldApplet into a generic string drawing applet. To do this we’ll need to pass the applet parameters that define the string to be drawn.

import java.applet.Applet;
import java.awt.Graphics;

public class DrawStringApplet extends Applet {

String input_from_page;

public void init() {
input_from_page = getParameter(”String”);
}

public void paint(Graphics g) {
g.drawString(input_from_page, 50, 25);
}

}

Now you need to create an HTML file that will include your applet. The following simple HTML file will do:



Draw String


This is the applet:




Of course you are free to change “Howdy, there!” to a string of your choice. Note that this allows you to change the output of the applet without changing or recompiling the code.

You’re not limited to one parameter either. You can pass as many named parameters to an applet as you like.

The getParameter method is straightforward. You give it a string that’s the name of the parameter you want. You get back a string that’s the value of the parameter. All parameters are passed as Strings. If you want to get something else like an integer then you’ll need to pass it as a String and convert it into the type you really want.

The PARAM HTML tag is also straightforward. It occurs between and . It has two parameters of its own, NAME and VALUE. The NAME identifies which parameter this is for the getParameter method. VALUE is the value of the parameter as a String. Both must be enclosed in double quote marks like all other HTML tag parameters.

Comments are closed.