An Overview of Java Applets

Java owes much of its early success and popularity to applets. Though its use has now dwindled due to competition from JavaScript and Flash, Java applet technology is still an important part of the web. An example usage of Java applets is to embed chat applications in web pages. Java applets are well suited to this because of the strong networking support inherent in the language.

Every Java applet extends the java.applet.Applet class. This class contains the following unimplemented methods that are called by the web browser to control the applet:

  • init() - Called when the page is loaded
  • start() - Called after init() and when the page is returned to (such as when pressing back)
  • stop() - Called when the user goes to another page
  • destroy() - Called when the browser exits (stop() will be called first)

Applets that want to use Swing user interface components should extend the class javax.swing.JApplet, which itself inherits from the Applet class. JApplet includes support for laying out Swing components in much the same way as a JFrame in Java application programming. In fact, because the framework behind both JApplets and JFrames is largely the same (they both derive from java.awt.Container), an applet can be converted to an application quite easily. It is also possible to structure a program so that it runs as both an applet and an application depending on the environment.

To run applets in a webpage, you must refer to the bytecode files from an <applet> or <object> tag (see below). In practice both tags are often included to cover as many platforms as possible. Applets can accept parameters from <param> tags embedded in the <applet> tags.

When Java applet technology was first released in 1995, only Sun's HotJava browser could run applets. However, Netscape and Microsoft soon added support to their browsers. As Java has evolved, though, most browsers have failed to provide support for the latest versions. Therefore, it is usually necessary to ensure your users have the Java plugin from Sun installed. The Java SDK includes a tool that can take your ordinary <applet> tags and convert them into more complicated <object> tags that will prompt the user to download and install the Java plugin if it is not already installed on their machine.