(^660) | Applets
(^1) Later versions of Java ease this restriction to allow special cases of file access when a user permits it.
14.1 What Is an Applet?
Applets are a kind of mini-application designed to be distributed along with Web pages and
run under a browser or applet viewer. They are used as elements of Web pages. Most Web
browsers include a special JVM that can execute the Bytecode version of an applet. When the
browser encounters a link to an applet Bytecode file, it copies the file into memory and calls
its JVM to execute the Bytecode.
The browser’s ability to execute applets enables us to create Web pages that are as so-
phisticated as almost any program we can write in Java. We say “almost” because applets are
subject to certain limitations that do not apply to Java applications. For example, you would
not want your browser to run an applet that destroys the files on your computer.Thus applets
are prohibited from accessing files.^1 Likewise, an applet cannot send messages to other com-
puters from your computer (except the one from which it was loaded). These security re-
strictions are included in Java to prevent the creation of harmful applets by malicious
programmers.
Applets differ from applications in several ways:
An applet doesn’t have a mainmethod. It is much more like a windowing
component than a stand-alone application.
An applet is not invoked in the same fashion as an application. Instead, it is
embedded within an HTML document. HTML is the language used to create Web
pages. We describe HTML briefly later in this chapter.
Applets are subjected to more security constraints than an application because
they are distributed over the Web.
Applets are not in control of their own execution. They simply respond when told
to do so by the browser or viewer.
Because of the way that applets are executed, they do not have constructors. Instead, the
operations that we would normally place into a constructor (such as initializing fields or
setting up the user interface) should be written in the applet’sinitmethod. When a browser
first downloads an applet, its JVM executes this method. In this chapter we use theinit
method not only to serve as a constructor but also to play the role ofmainin an application.
It contains the main block of code that begins the work of the applet.
Whereas all applications are usually derived implicitly from Object, applets must be ex-
plicitly derived from the Appletor JAppletclass, both of which are descendants of the class
Container. These classes contain additional methods called start,stop, and destroythat are
used with more sophisticated applets that employ features of Java not covered in this text.
For example, if an applet is showing a graphics animation, we may want it to stop when the
user moves to a different Web page and resume (start) when the user returns to the page with
the applet.
T
E
A
M
F
L
Y
Team-Fly®