How to Passing Parameters to Applets ?
Parameters are passed to applets in NAME=VALUE pairs in tags among the opening and closing APPLET tags. Inside the applet, you read the values passed by the PARAM tags along with the getParameter() techniques of the java.applet.Applet class.
The program below demonstrates this along with a generic string drawing applet. The applet parameter "Message" is the string to be drawn.
import java.applet.*;
import java.awt.*;
public class DrawStringApplet extends Applet {
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 25);
}
}
You also need an HTML file that references your applet. The subsequent simple HTML file will do:
< HTML>
< HEAD>
< TITLE> Draw String
< /HEAD>
< BODY>
This is the applet:
< APPLET code="DrawStringApplet" width="300" height="50">
< PARAM name="Message" value="Howdy, there!">
This page will be very boring if your
browser doesn't understand Java.
< /APPLET>
< /BODY>
< /HTML>
Of course you are free to change "Howdy, there!" to a "message" of your choice. You only required to change the HTML, not the Java source code. PARAMs let you customize applets without changing or recompiling the code.
This applet is very similar to the HelloWorldApplet. Therefore rather than hardcoding the message to be printed it's read within the variable inputFromPage from a PARAM element in the HTML.
You pass getParameter() a string that names the parameter you want. This string should match the name of a PARAM element in the HTML page. getParameter() returns the value of the parameter. All values are passed as strings. If you want to get another type like an integer, then you'll requires passing it as a string and converting it to the type you really need.
The PARAM element is also straightforward. It occurs among . It has two attributes of its own, NAME and VALUE. NAME identifies that PARAM this is. VALUE is the string value of the PARAM. Both should be enclosed in double quote marks if they contain white space.
An applet is not limited to one PARAM. You can pass as several named PARAMs to an applet as you like. An applet does not necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can be safely ignored.