Recipe 18.2 Applet Techniques


You need to write an applet.


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 (see the See Also section at the end of this recipe).


The four Applet "lifecycle" methods that an applet writer can implement are init( ) , start( ), stop( ), and destroy( ) (see Table 18-2). The applet's lifecycle 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 18-2. Applet methods

Method name


init( )

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

start( )

The page is loaded, or reloaded, or revisited via the Back button...

stop( )

The user is leaving this page, or the applet is scrolled off-screen...

destroy( )

The applet is being unloaded.

Applets normally use their init( ) method to initialize their state, the same functionality as a constructor in a nonapplet class. This may seem a bit odd for those used to constructors in an OO language. However, it is mandatory for any methods that call applet-specific methods, such as the all-important getParameter( ). Why? In brief, because the browser first constructs the applet always with the no-argument constructor form, which is much easier for the browser (see Recipe Recipe 25.3 for the reasons) and then call its setStub( ) method.[2] The AppletStub is an object provided by the browser, which provides a getAppletContext( ) method, which of course returns an AppletContext object. These objects are both delegates (in the design patterns sense). The AppletStub object contains the actual implementation of important methods like getParameter( ) , getCodeBase( ), and getDocumentBase( ). The AppletContext object contains the real implementations of most other applet-specific routines, including showStatus( ) , getImage( ), and showDocument( ).

[2] It didn't have to be this way. At the beginning of Java browserdom, they could have said, "Let's just pass in the applet stub as an argument when constructing the applet." But they didn't "and now it's too late," as Dr. Seuss once said.

So, an applet's constructor can't call getParameter( ), getImage( ), or showStatus( ) because the AppletStub isn't set until the applet's constructor returns. About the most a constructor can do is add GUI elements. Therefore, it is generally preferable to do all the applet's initialization in one place, so it might as well be the init( ) method, which the browser calls only once for each applet instance. This is why, in practice, most applets don't have any constructors: the default (no-argument) constructor is the only one ever called.

The start( ) method is called when the browser has fully loaded the applet and it's ready to go. It may be called again when the user moves back onto the page, scrolls back so the applet is shown again, and so on. This is the normal time for your applet to start threads (Chapter 24), audio or video (see Chapter 13), or anything else that takes time. The stop( ) method is called when the user gets bored and leaves the page.

The least commonly used applet method is destroy( ); it is called when the browser removes your applet instance from memory and allows you to close files, network connections, etc. After that, it's all over.

All four methods are public, all return void, and all take no arguments. They are shown together in Example 18-1.

Example 18-1.
import java.applet.*; import java.awt.*; import*; /** AppletMethods -- show stop/start and AudioClip methods */ public class AppletMethods extends Applet {     /** AudioClip object, used to load and play a sound file. */     AudioClip snd = null;     /** Initialize the sound file object and the GUI. */     public void init( ) {         System.out.println("In AppletMethods.init( )");         try {             snd = getAudioClip(new URL(getCodeBase( ), ""));         } catch (MalformedURLException e) {             showStatus(e.toString( ));         }         setSize(200,100);    // take the place of a GUI     }     /** Called from the Browser when the page is ready to go. */     public void start( ) {         System.out.println("In AppletMethods.start( )");         if (snd != null)    );    // loop( ) to be obnoxious...     }     /** Called from the Browser when the page is being vacated. */     public void stop( ) {         System.out.println("In AppletMethods.stop( )");         if (snd != null)             snd.stop( );    // stop play( ) or loop( )      }     /** Called from the Browser (when the applet is being un-cached?).      * Not actually used here, but the println will show when it's called.      */     public void destroy( ) {         System.out.println("In AppletMethods.destroy( )");     }     public void paint(Graphics g) {         g.drawString("Welcome to Java", 50, 50);     }     /** An alternate form of getParameter that lets      * you provide a default value, since this is so common.      */     public String getParameter(String p, String def) {         return getParameter(p)==null?def:getParameter(p);     } }

See Also

Applets based on Applet and using AWT work on most browsers. Applets based on JApplet and/or using Swing components need the Java Plug-in (see Recipe Recipe 23.6) to ensure that a compatible runtime is available.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: