Animation by Example: More About HTML for Applets
by David Matuszek

The basic HTML for running an applet looks like this:

<html>
  <head>
    <title>This is my Applet</title>
  </head>
  <body>
    <applet code="MyApplet.class" width="250" height="60">
    </applet>
  </body>
</html>

The height and width parameters are required; they tell the browser how big to make the applet. If you use appletviewer, the window can be resized, otherwise it can't.

You must have either a code= or an archive= parameter. Use code= in order to specify your main Applet class, and use archive= to specify a .jar file. If your applet has more than one class, the browser will figure that out and load them all, one at a time. Loading many classes over the web is much slower than putting all your classes in a jar file and loading just that one file.

If you want to pass parameters to your applet, you can do this by putting param tags between <applet ...> and </applet>, like this:

<applet code="MyApplet.class" width="250" height="60">
  <param name="delay" value="50">
  <param name="version" value="Version 1.0">
</applet>

Within your class that extends Applet, you can retrieve these parameters by calling getParameter(String name), which returns a String value. If you want to convert this String to an int, an easy way to do it is:

intValue = Integer.valueOf(getParameter("delay")).intValue();

It is a very good idea to use lots of Applet parameters, because when you are trying a lot of variations to get things just right, it's much faster to just change the HTML file and reload it, than to edit the Java file, save it, recompile it, and reload the HTML.

Sneaky trick: appletviewer ignores everything in the file that you give it except the applet tags. You can avoid having a separate .html file by putting the applet tags inside a comment inside your Java program. Like this:

// <applet code="Bounce.class" width="320" height="220">  </applet>

This is handy when you're debugging your program with appletviewer, but your browser won't understand it. You really do need a separate HTML file for the browser.

Previous