Applet Techniques

Problem

You need to write an applet.

Solution

Write a class that extends java.applet.Applet or javax.swing.JApplet, and use some or all of the applet methods. Start with Applet if you want to use plain AWT and be portable to all browsers; use JApplet if you want Swing capabilities in your applet (but see the note at the end of this recipe under Section 17.3.4).

Discussion

The four Applet “life cycle” methods that an applet writer can implement are init( ) , start( ), stop( ), and destroy( ) (see Table 17-2). The applet’s life cycle is more complex than that of a regular application, since the user can make the browser move to a new page, return to a previous page, reload the current page, etc. What’s a poor applet to do?

Table 17-2. Applet methods

Method name

Function

init(  )

Initialize the applet (takes the place of a constructor).

start(  )

The page is loaded, and we’re ready to display.

stop(  )

The user is leaving this page.

destroy(  )

The applet is being unloaded.

Applets normally use their init( ) method to initialize their state, the same functionality as a constructor in a non-applet class. This may seem a bit odd for those used to constructors in an OO language. However, it is mandatory for any methods that will call applet-specific methods, such as the all-important getParameter( ). Why? In brief, because the browser will first construct the applet -- always with the no-argument constructor form, which is much easier for the browser (see ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.