Java Applets
An
applet is a program that runs inside a web page when that page is displayed by
a Java-capable browser. An applet can
also be displayed using Sun's appletviewer utility. An applet lives in a strictly event driven
environment. There are five events in
the life of an applet and each of them have applet
methods which are executed when the event occurs.
·
When the applet is loaded the browser calls the init() method of the applet class.
This method is called only once, when
the applet is loaded.
·
Next the start()
method is called. The start() method is called every time the
applet page is accessed. If you leave
the web page and then click the back button on the browser the start() method is called again.
·
Once the applet is loaded and started the paint() method is called. This
method is called every time the browser needs to display the applet on the
screen. The paint() method can be used to display
anything including text and graphics.
The browser passes the paint() method a Graphics object. This Graphics
object is used to display items on the screen. The Graphics
object is passed to the paint() method as
an argument.
·
Any time you leave the web page containing your applet the stop() method is called. If you return to the web page containing your
applet the start() method is called again.
·
Finally, when the browser exits altogether the destroy() method is called.
The
main class of an applet is a class that extends
the Applet class by inheritance. This Applet
class is part of the Java applet package. The Graphics
class is part of the Java abstract windows toolkit (awt)
package. Since these two classes are not
part of the actual language (they are in the Java class packages) we must tell the Java compiler to import these classes. We do this with the import command:
import java.applet.Applet;
import java.awt.Graphics;
In
this way we can import any packages, including ones we might write.
There
is no main() method in an applet because an applet
does not start itself like an application does.
An applet is added to an already running program (the browser). The browser runs the applet by calling
methods it knows the applet has (see above).