The init()
method is called exactly once in an
applet's life, when the applet is first loaded. It's normally used
to read PARAM tags, start downloading any other images or media
files you need, and set up the user interface. Most applets have
init()
methods.
The start()
method is called at least once in an
applet's life, when the applet is started or restarted. In some
cases it may be called more than once. Many applets you write will
not have explicit start()
methods and will merely
inherit one from their superclass. A start()
method is
often used to start any threads the applet will need while it
runs.
The stop()
method is called at least once in an
applet's life, when the browser leaves the page in which the applet
is embedded. The applet's start()
method will be
called if at some later point the browser returns to the page
containing the applet. In some cases the stop()
method
may be called multiple times in an applet's life. Many applets you
write will not have explicit stop()
methods and will
merely inherit one from their superclass. Your applet should use
the stop()
method to pause any running threads. When
your applet is stopped, it should not use any CPU
cycles.
The destroy()
method is called exactly once in an
applet's life, just before the browser unloads the applet. This
method is generally used to perform any final clean-up. For
example, an applet that stores state on the server might send some
data back to the server before it's terminated. many applets will
not have explicit destroy()
methods and just inherit
one from their superclass.
For example, in a video applet, the init()
method
might draw the controls and start loading the video file. The
start()
method would wait until the file was loaded,
and then start playing it. The stop()
method would
pause the video, but not rewind it. If the start()
method were called again, the video would pick up where it left
off; it would not start over from the beginning. However, if destroy()
were called and then init()
, the
video would start over from the beginning.
In the JDK's appletviewer, selecting the Restart menu item calls
stop()
and then start()
. Selecting the
Reload menu item calls stop()
, destroy()
,
and init()
, in that order. (Normally the byte codes
will also be reloaded and the HTML file reread though Netscape has
a problem with this.)
The applet start()
and stop()
methods
are not related to the similarly named methods in the java.lang.Thread
class.
Your own code may occasionally invoke start()
and
stop()
. For example, it's customary to stop playing an
animation when the user clicks the mouse in the applet and restart
it when they click the mouse again.
Your own code can also invoke init()
and destroy()
, but this is normally a bad idea. Only the
environment should call init()
and destroy()
.