| Developer's Daily | Java Education |
| front page | java | perl | unix | DevDirectory |
Introduction
Many times when you're developing Java applets, you want to pass parameters from an HTML page to the applet you're invoking. For instance, you may want to tell the applet what background color it should use, or what font to use, to keep your applet consistent with the rest of your web site.
A great benefit of passing parameters from HTML pages to the applets they call is portability. If you pass parameters into your applets, they can be portable from one web page to another, and from one web site to another. On the other hand, if you don't pass parameters into your Java applets, how will the applet know what font to use? Simple - you hardwire it into the Java source code! As I often say to my new puppy at home, "this is bad".
In this brief article, we'll show you how to pass several parameters
from an HTML page to a Java applet. Hopefully you'll be able to use
this same technique to make your own applets more flexible and portable.
The sample HTML file
Listing 1 shows the source code for the sample HTML file we created
for this article. We named this file ParamTest.html.
|
<HTML>
|
| Listing 1: | ParamTest.html - an HTML file that calls a Java applet, and passes several parameters to the applet via the <PARAM> tag. |
The ParamTest.java file
So far we've seen to create the HTML code that (1) invokes a Java applet and (2) passes parameters to the applet. Next, let's look at the Java code needed to read the parameters being passed to it. Listing 2 shows the Java code for the ParamTest.java file.
As you can see, this is a fairly simple applet. It simply retrieves the parameters passed to it with the getParameter() method, then uses those parameters to construct it's output. In this case the few parameters we've passed in deal with the font and the string to be printed. In a more elaborate example we might pass in more parameters dealing with the applet colors.
|
import java.applet.*;
public class ParamTest extends Applet { public void paint(Graphics g) { String myFont = getParameter("font");
Font f = new Font(myFont, Font.BOLD,
mySize);
} }
|
| Listing 2: | The source for ParamTest.java demonstrates how parameters can be passed into Java applets. |
Try the on-line demo, and download the source
If you'd like to see the ParamTest applet in action, click here. Of course, once that page is loaded you can also save the HTML source code once it's loaded into your browser.
Click here if you'd like to view/download the ParamTest.java source code.
Copyright 1998-2008 DevDaily Interactive, Inc.
All Rights Reserved.