Starting and Stopping Applets
Five methods are essential in every applet:
- When the browser first loads a page containing an applet the
init() method of that applet is called.
In most cases it is safe to operate on Swing components in the
init method.
A common error is not to expect init to be called
multiple times.
Each time the browser finds it necessary to pass the input parameters
to an applet the init method is called.
- Whenever the browser (re)visits a page containing an applet the
start() method of that applet is called.
A video or sound clip may wish to start from the top again.
start is called after init.
- Whenever the browser needs to redisplay an AWT applet
(for example after part
of it was obscured by another window) the paint() method
is called. Updating Swing applets is done automatically.
If updating fails for some reason (bug!) a component's
repaint() method can be called.
- Whenever the browser leaves the page containing an applet the
stop() method of that applet is called.
The applet should stop hogging system resources while not being displayed.
When an applet starts separate threads the stop method
should be overridden so it suspends the other threads.
- destroy() may be called when the browser (actually,
the Java Virtual Machine) needs to reclaim memory and wishes to unload
a non-active applet entirely. This method can do some final cleanup.
destroy is called after the stop
method. It cannot be used to prevent being destroyed. (But it can be used
to stall that process...)
Below is (most of) the source code for a small applet that notifies a WWW
server when the user leaves a page:
public class Stop extends Applet {
URL stopURL = null;
String host = null;
public void init() {
try {
stopURL = new URL(getParameter("STOPURL"));
host = getParameter("host");
} catch (MalformedURLException e) { ; }
}
public void start() { }
public void stop() {
Socket s = null;
try {
s = new Socket(host, 80);
PrintStream server_out = new PrintStream(s.getOutputStream());
server_out.println("GET " + getParameter("STOPURL") + " HTTP/1.0");
server_out.println(""); server_out.println("");
} catch (IOException e) { System.out.println(e); }
finally {
try { if (s != null) s.close(); }
catch (IOException e2) { ; }
}
}
}