|
Previous Next
Applet Parameters
The Java application receives its parameter through the main methods. The Java applet receives its parameters through the <PARAM> tags in the HTML page. There are 2 parts for each parameter, the NAME of the parameter and the VALUE of the parameter. For example:
<PARAM NAME="Score" VALUE="89">
In this example, the name of the parameter is Score and its value is 89.
In the following example, we will enter Font information as parameters to our applet. The HTML page is
<HTML>
<HEAD>
<TITLE>Pick up Parameters in an applet</TITLE>
</HEAD>
<BODY>
Before the Applet...
<APPLET CODE="TextFontApplet.class" WIDTH="400" HEIGHT="25">
<PARAM NAME="FntName" VALUE="Book Antiqua">
<PARAM NAME="FntSize" VALUE="20">
<PARAM NAME="txtColor" VALUE="#ee00ff">
</APPLET>
After
</BODY>
</HTML>
The java code follows. Note that the getParameter method is used to pick up the PARAM values when you specify the PARAM name. If the parameter is not a string, it has to be converted to the needed format. If no parameter was entered (== null), then a default value is set.
import java.applet.*;
import java.awt.*;
public class TextFontApplet extends Applet {
String fName;
Font font;
int fSize;
Color tColor;
public void init() {
fName = getParameter("fntName");
if (fName == null) fName = "Monospaced";
String sz = getParameter("fntSize");
if (sz == null) fSize = 12;
else fSize = Integer.parseInt(sz);
String clr = getParameter("txtColor");
if (clr == null) tColor = Color.red;
if (clr != null) {
try {
tColor = Color.decode(clr);
} catch (NumberFormatException e) {
showStatus("Invalid txtColor parameter " + clr);
tColor = Color.red;
}
}
font = new Font(fName, Font.BOLD, fSize);
}
public void paint(Graphics g) {
g.setColor(tColor);
g.setFont(font);
g.drawString("Hello world! in " + fName + " " + fSize, 10, 25);
}
}
The test run gives the following.
Remember that if you make changes to your applet and the changes don't seem to be working, try closing your browser window and try again to open your HTML page. This should clear the old copy in the buffer (memory) and make it look on your disk for a new copy.
Previous Next
|