Applet HTML Tags and Attributes
In its most basic form, an example for using the applet tag looks like this:
As you have seen, the code attribute gives the name of the class file and must include the .class extension; the width and height attributes size the window that will hold the applet. Both are measured in pixels. You also need a matching </applet> tag that marks the end of the HTML tagging needed for an applet. The text between the <applet> and </applet> tags is displayed only if the browser cannot show applets. These tags are required. If any are missing, the browser cannot load your applet. All of this information would usually be embedded in an HTML page that, at the very least, might look like this:
The next line of text is displayed under the auspices of Java:
If your browser could show Java, you would see an applet here.
According to the HTML specification, the HTML tags and attributes such as applet can be in upper- or lowercase. We use lowercase because that is the recommendation of the newer XHTML specification. However, the name of the applet class is case-sensitive! The letter case may be significant in other attributes, such as names of JAR files, if the web server file system is case sensitive.
Applet Attributes for Positioning
What follows are short discussions of the various attributes that you can (or must) use within the applet tag to position your applet. For those familiar with HTML, many of these attributes are similar to those used with the IMG tag for image placement on a web page.
- width, height
These attributes are required and give the width and height of the applet, measured in pixels. In the applet viewer, this is the initial size of the applet. You can resize any window that the applet viewer creates. In a browser, you cannot resize the applet. You will need to make a good guess about how much space your applet requires to show up well for all users.
This attribute specifies the alignment of the applet. There are two basic choices. The applet can be a block with text flowing around it, or the applet can be inline, floating inside a line of text as if it were an oversized text character. The first two values (left and right) make the text flow around the applet. The others make the applet flow with the text.
The choices are described in Table 10-1.
Table 10-1. Applet positioning attributes
Screenshot-6 shows all alignment options for an applet that floats with the surrounding text. The vertical bar at the beginning of each line is an image. Since the image is taller than the text, you can see the difference between alignment with the top or bottom of the line and the top or bottom of the text.
What It Does
Places the applet at the left margin of the page. Text that follows on the page goes in the space to the right of the applet.
Places the applet at the right margin of the page. Text that follows on the page goes in the space to the left of the applet.
Places the bottom of the applet at the bottom of the text in the current line.
Places the top of the applet with the top of the current line.
Places the top of the applet with the top of the text in the current line.
Places the middle of the applet with the baseline of the current line.
Places the middle of the applet with the middle of the current line.
Places the bottom of the applet with the baseline of the current line.
Places the bottom of the applet with the bottom of the current line.
These optional attributes specify the number of pixels above and below the applet (vspace) and on each side of the applet (hspace).
Screenshot-6. Applet alignment
Applet Attributes for Code
The following applet attributes tell the browser how to locate the applet code; here are short descriptions.
This attribute gives the name of the applet's class file. This name is taken relative to the codebase (see below) or relative to the current page.
If you use a relative path name, then the path name must match the package of the applet class. For example, if the applet class is in the package com.mycompany, then the attribute is code="com/mycompany/MyApplet.class". The alternative code="com.mycompany.MyApplet.class" is also permitted. But you cannot use absolute path names here. Use the codebase attribute if your class file is located elsewhere.
The code attribute specifies only the name of the class that contains the applet class. Of course, your applet may contain other class files. Once the browser's class loader loads the class containing the applet, it will realize that it needs more class files, and will load them.
Either the code or the object attribute (see below) is required.
This optional attribute tells the browser that your class files are found below the directory indicated in the codebase attribute. For example, if an applet called CalculatorApplet is in the directory MyApplets, and the MyApplets directory is below the location of the web page, you would use:
<applet code="CalculatorApplet.class" codebase="MyApplets"
In other words, the file layout looks like this:
This optional attribute lists the Java archive file or files containing classes and other resources for the applet. (See the section on JAR files later in this chapter for more on Java archive files.) These files are fetched from the web server before the applet is loaded. This technique speeds up the loading process significantly since only one HTTP request is necessary to load a JAR file that contains many smaller files. The JAR files are separated by commas. For example:
<applet code="CalculatorApplet.class" archive=
As another way to specify the applet class file, you can specify the name of a file that contains the serialized applet object, but browsers vary in support of this attribute. You will definitely need to use the Java Plug-In if you want to use this feature. (An object is serialized when you write all its data fields to a file. We will discuss serialization in .) The object is deserialized from the file to return it to its previous state. When you use this attribute, the init method is not called, but the applet's start method is called. Before serializing an applet object, you should call its stop method. This feature is useful for implementing a persistent browser that automatically reloads its applets and has them return to the same state that they were in when the browser was closed. This is a specialized feature, not normally encountered by web page designers.
Either code or object must be present in every applet tag. For example,
You can then refer to the object as document.applets.appletname. For example,
var calcApplet = document.applets.calc;
(Our calculator applet doesn't have a clear method; we just want to show you the syntax.)
The name attribute is also essential when you want two applets on the same page to communicate with each other directly. You specify a name for each current applet instance. You pass this string to the getApplet method of the AppletContext class. We will discuss this mechanism, called inter-applet communication, later in this chapter.
Applet Attributes for Java-Challenged Viewers
If a web page containing an applet tag is viewed by a browser that is not aware of Java applets, then the browser ignores the unknown applet and param tags. All text between the <applet> and </applet> tags is displayed by the browser. Conversely, Java-aware browsers do not display any text between the <applet> and </applet> tags. You can display messages inside these tags for those poor folks that use a prehistoric browser. For example,
If your browser could show Java, you would see a calculator here.
Of course, nowadays most browsers know about Java, but Java may be deactivated, perhaps by the user or by a paranoid system administrator. You can then use the alt attribute to display a message to these unfortunate souls.
alt="Java If your browser could show Java, you would see
a calculator here">
The object Tag
The object tag is part of the HTML 4.0 standard, and the W3 consortium suggests that people use it instead of the applet tag. There are 35 different attributes to the object tag, most of which (such as onkeydown) are relevant only to people writing Dynamic HTML. The various positioning attributes such as align and height work exactly as they did for the applet tag. The key attribute in the object tag for your Java applets is the classid attribute. This attribute specifies the location of the object. Of course, object tags can load different kinds of objects, such as Java applets or ActiveX components like the Java Plug-In itself. In the code attribute, you specify the nature of the object. For example, Java applets have a code type of app/java. Here is an objecct tag to load a Java applet:
Note that the classid attribute can be followed by a codebase attribute that works exactly as it did with the applet tag.
Passing Information to Applets
Just as apps can use command-line information, applets can use parameters that are embedded in the HTML file. This is done via the HTML tag called param along with attributes that you define. For example, suppose you want to let the web page determine the style of the font to use in your applet. You could use the following HTML tags:
<applet code="FontParamApplet.class" >
You then pick up the value of the parameter, using the getParameter method of the Applet class, as in the following example:
public class FontParamApplet extends JApplet
public void init()
String fontName = getParameter("font");
. . .
. . .
Parameters are always returned as strings. You need to convert the string to a numeric type if that is what is called for. You do this in the standard way by using the appropriate method, such as parseInt of the Integer class. For example, if we wanted to add a size parameter for the font, then the HTML code might look like this:
You can call the getParameter method only in the init method of the applet, not in the constructor. When the applet constructor is executed, the parameters are not yet prepared. Since the layout of most nontrivial applets is determined by parameters, we recommend that you don't supply constructors to applets. Simply place all initialization code into the init method.
<applet code="FontParamApplet.class" >
The following source code shows how to read the integer parameter.
public class FontParamApplet extends JApplet
public void init()
String fontName = getParameter("font");
int fontSize = Integer.parseInt(getParameter("size"));
. . .
In addition to ensuring that the parameters match in your code, you should find out whether or not the size parameter was left out. You do this with a simple test for null. For example:
The strings used when you define the parameters via the param tag and those used in the getParameter method must match exactly. In particular, both are case sensitive.
String sizeString = getParameter("size");
if (sizeString == null) fontSize = 12;
else fontSize = Integer.parseInt(sizeString);
Here is a useful applet that uses parameters extensively. The applet draws a bar chart, shown in Screenshot-7.
Screenshot-7. A chart applet
The applet takes the labels and the heights of the bars from the param values in the HTML file. Here is what the HTML file for Screenshot-7 looks like:
<applet code="Chart.class" >
<param value="Diameters of the Planets"/>
<param name="name.1" value="Mercury"/>
<param name="name.2" value="Venus"/>
<param name="name.3" value="Earth"/>
<param name="name.4" value="Mars"/>
<param name="name.5" value="Jupiter"/>
<param name="name.6" value="Saturn"/>
<param name="name.7" value="Uranus"/>
<param name="name.8" value="Neptune"/>
<param name="name.9" value="Pluto"/>
<param name="value.1" value="3100"/>
<param name="value.2" value="7500"/>
<param name="value.3" value="8000"/>
<param name="value.4" value="4200"/>
<param name="value.5" value="88000"/>
<param name="value.6" value="71000"/>
<param name="value.7" value="32000"/>
<param name="value.8" value="30600"/>
<param name="value.9" value="1430"/>
You could have set up an array of strings and an array of numbers in the applet, but there are two advantages to using the param mechanism instead. You can have multiple copies of the same applet on your web page, showing different graphs: just put two applet tags with different sets of parameters on the page. And you can change the data that you want to chart. Admittedly, the diameters of the planets will stay the same for quite some time, but suppose your web page contains a chart of weekly sales data. It is easy to update the web page because it is plain text. Editing and recompiling a Java file on a weekly basis is more tedious. In fact, there are commercial Java beans that make much fancier graphs than the one in our chart applet. If you buy one, you can drop it into your web page and feed it parameters without ever needing to know how the applet renders the graphs. Example 10-5 is the source code of our chart applet. Note that the init method reads the parameters, and the paintComponent method draws the chart.
Example 10-5 Chart.java
1. import java.awt.*;
2. import java.awt.font.*;
3. import java.awt.geom.*;
4. import javax.swing.*;
6. public class Chart extends JApplet
8. public void init()
10. String v = getParameter("values");
11. if (v == null) return;
12. int n = Integer.parseInt(v);
13. double values = new double[n];
14. String names = new String[n];
15. int i;
16. for (i = 0; i < n; i++)
18. values[i] = Double.parseDouble
19. (getParameter("value." + (i + 1)));
20. names[i] = getParameter("name." + (i + 1));
23. Container contentPane = getContentPane();
24. contentPane.add(new ChartPanel(values, names,
30. A panel that draws a bar chart.
32. class ChartPanel extends JPanel
35. Constructs a ChartPanel.
36. @param v the array of values for the chart
37. @param n the array of names for the values
38. @param t the title of the chart
40. public ChartPanel(double v, String n, String t)
42. names = n;
43. values = v;
44. title = t;
47. public void paintComponent(Graphics g)
50. Graphics2D g2 = (Graphics2D)g;
52. // compute the minimum and maximum values
53. if (values == null) return;
54. double minValue = 0;
55. double maxValue = 0;
56. for (int i = 0; i < values.length; i++)
58. if (minValue > values[i]) minValue = values[i];
59. if (maxValue < values[i]) maxValue = values[i];
61. if (maxValue == minValue) return;
63. int panelWidth = getWidth();
64. int panelHeight = getHeight();
66. Font titleFont = new Font("SansSerif", Font.BOLD, 20);
67. Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
69. // compute the extent of the title
70. FontRenderContext context = g2.getFontRenderContext();
71. Rectangle2D titleBounds
72. = titleFont.getStringBounds(title, context);
73. double titleWidth = titleBounds.getWidth();
74. double top = titleBounds.getHeight();
76. // draw the title
77. double y = -titleBounds.getY(); // ascent
78. double x = (panelWidth - titleWidth) / 2;
80. g2.drawString(title, (float)x, (float)y);
82. // compute the extent of the bar labels
83. LineMetrics labelMetrics
84. = labelFont.getLineMetrics("", context);
85. double bottom = labelMetrics.getHeight();
87. y = panelHeight - labelMetrics.getDescent();
90. // get the scale factor and width for the bars
91. double scale = (panelHeight - top - bottom)
92. / (maxValue - minValue);
93. int barWidth = panelWidth / values.length;
95. // draw the bars
96. for (int i = 0; i < values.length; i++)
98. // get the coordinates of the bar rectangle
99. double x1 = i * barWidth + 1;
100. double y1 = top;
101. double height = values[i] * scale;
102. if (values[i] >= 0)
103. y1 += (maxValue - values[i]) * scale;
106. y1 += maxValue * scale;
107. height = -height;
110. // fill the bar and draw the bar outline
111. Rectangle2D rect = new Rectangle2D.Double(x1, y1,
112. barWidth - 2, height);
118. // draw the centered label below the bar
119. Rectangle2D labelBounds
120. = labelFont.getStringBounds(names[i], context);
122. double labelWidth = labelBounds.getWidth();
123. x = i * barWidth + (barWidth - labelWidth) / 2;
124. g2.drawString(names[i], (float)x, (float)y);
128. private double values;
129. private String names;
130. private String title;
- public String getParameter(String name)
gets a parameter defined with a param directive in the web page loading the applet. The string is case sensitive.
- public String getAppletInfo()
is a method that many applet authors override to return a string that contains information about the author, version, and copyright of the current applet. You need to create this information by overriding this method in your applet class.
- public String getParameterInfo()
is a method that many applet authors override to return an array of param tag options that this applet supports. Each row contains three entries: the name, the type, and a description of the parameter. Here is an example:
"fps", "1-10", "frames per second"
"repeat", "boolean", "repeat image loop?"
"images", "url", "directory containing images"