Download - Passing Parameter to Applet
-
8/6/2019 Passing Parameter to Applet
1/3
-
8/6/2019 Passing Parameter to Applet
2/3
A great benefit of passing applet parameters from HTML pages to the applets they call is
portability. If you pass parameters into your Java 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 a Java applet, 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 applet tutorial, we'll show you how to pass applet 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
The listing below shows the source code for the sample HTML file we created for this
article, including the applet tag shown. We name this fileAppletParameterTest.html .
Java applet example - Passing applet parameters to Java
applets
As you can see, the HTML file identifies the Java applet that we want to load -
AppletParameterTest.class using an APPLET tag. Then, the only thing we need to do to
pass parameters to the applet are to include the name and value of the desired parameters
in tags. These names and values can be whatever we want - whatever makes
-
8/6/2019 Passing Parameter to Applet
3/3
sense for your applet. As a final note, notice that the tags are enclosed within
the tags.
The ParamTest.java file
So far we've seen to create the HTML code that (1) invokes a Java applet using an applet
tag, and (2) passes parameters to the applet. Next, let's look at the Java applet code
needed to read the parameters being passed to it. The next listing shows the Java code for
the ParamTest.java file.
import java.applet.*;
import java.awt.*;
/**
* A Java applet parameter test class.* Demonstrates how to read applet parameters.
*/
public class AppletParameterTest extends Applet {
public void paint(Graphics g) {
String myFont = getParameter("font");
String myString = getParameter("string");
int mySize = Integer.parseInt(getParameter("size"));
Font f = new Font(myFont, Font.BOLD, mySize);
g.setFont(f);
g.setColor(Color.red);
g.drawString(myString, 20, 20);
}
}
As you can see, this is a fairly simple Java applet. It retrieves the applet parameters passed
to it with the getParameter() method, then uses those parameters to construct its 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 applet parameters to
customize the applet's appearance.