Java Reference
In-Depth Information
CHAPTER 15
Applets
This chapter demonstrates the techniques of applet writing. It proceeds from a
trivial “Hello World” applet to more sophisticated applets. Along the way, it
explains how to:
•
Draw graphics in your applet
•
Handle and respond to simple user input
•
Read and use values of applet parameters, allowing customization of an
applet
•
Load and display images and load and play sounds
•
Package an applet and related files into a JAR file
Introduction to Applets
An applet, as the name implies, is a kind of mini-application, designed to be run
by a web browser or in the context of some other “applet viewer.” Applets differ
from regular applications in a number of ways. One of the most important is that
there are a number of security restrictions on what applets are allowed to do. An
applet often consists of untrusted code, so it cannot be allowed access to the local
filesystem, for example.
All applets subclass
java.applet.Applet
, which inherits from
java.awt.Panel
and
java.awt.Component
. So creating an applet is more like subclassing a GUI compo-
nent than it is like writing an application. In particular, an applet does not have a
main()
method or other single entry point from which the program starts running.
Instead, to write an applet, you subclass
Applet
and override a number of stan-
dard methods. At appropriate times, under well-defined circumstances, the web
browser or applet viewer invokes the methods you have defined. The applet is not
in control of the thread of execution; it simply responds when the browser or
viewer tells it to. For this reason, the methods you write must take the necessary
action and return promptly; they are not allowed to enter time-consuming (or