An applet extends a panel, so it "is" a component of the AWT. But how come it runs as a program?
init
, for the initialization of
the applet. It is called automatically by the JVM.start
is done and
then a call
to the paint
routine.
Once a browser has loaded an applet, this applet will stay running. Also when the applet is not visible, it is still running in the background. This is even the case when you have clicked to other URLs. Only when you quit the browser, the applet will exit as well.
The stop
method is exactly meant to keep in control
of the applet at these moments where the applet becomes
not visible. By implementing this method,
you can stop computations or "threads" like
animations. In general you should stop
parts of the programs that consume resources.
Of course, once you can stop things, you should be able
to restart them as well. For this purpose, there is
the start
method. This method is also automatically
called at the beginning, just after init
.
When you ask the browser to reload a page containing the applet,
it will call stop, immediately followed by start.
Just before exiting, so when the browser quits,
the applet performs a call to the destroy
method. Here
some clean-up code can be inserted, however this is
in practice seldomly necessary. Please note the difference with the
stop method.
As we now have all ingredients that make up an applet, we can mimick the browser with a simple Java application. The JDK appletviewer offers more functionality, but essentially does the same. So all we have to do is to make a frame, and then perform the necessary calls to init, start, stop and destroy. Here is the essential part of the code.
class AppletFramer extends Frame { Applet applet; AppletFramer (String appletname, int width, int height) { setLayout(new BorderLayout()); try { // get the class from its name and instantiate it applet = (Applet) Class.forName(appletname).newInstance(); } catch (Exception e) { System.out.println(e); } resize(width, height); add("Center", applet); // the applet is a panel applet.init(); applet.start(); show(); } public boolean handleEvent (Event evt) { if (evt.id == Event.WINDOW_DESTROY) { applet.destroy(); dispose(); System.exit(0); } else if (evt.id == Event.WINDOW_ICONIFY) { applet.stop(); } else if (evt.id == Event.WINDOW_DEICONIFY) { applet.start(); } return super.handleEvent(evt); } }