Java Reference
In-Depth Information
16.3
Java applets
A web page is written in a language called
html
, which stands for
HyperText
Markup Language
. Web pages can contain
applets
, which are Java programs
written in a special way. In this section, we show you how to write an applet. In
Sec. 16.4, we discuss html and show you how to put an applet in a web page.
An applet is a Java class (together with other classes that it uses) that is a
subclass of class java.applet.
Applet
. Class
JApplet
, in package
javax.swing
,
is a subclass of
Applet
, and people prefer to use
JApplet
rather than
Applet
.
Class
Applet
(and therefore
JApplet
) has the five procedures listed below,
which are inherited in any subclass. The procedures have empty bodies and can
be overridden.
Activity
16-1.2
1.
paint(Graphics g)
: called to paint the applet's panel
2.
init()
: called to initialize the applet
3.
start()
: called to tell the applet to start processing
4.
stop()
: called to tell the applet to stop processing
5.
destroy()
: called to tell the applet to terminate its activities
The structure of an applet computation
When a browser loads a page that contains an applet, it starts the applet with
these two calls:
Activity
16-1.3
init(); start();
Procedure
init
is supposed to initialize the applet, and procedure
start
is
supposed to start any computation that the applet has to perform.
The browser also calls method
paint
to paint the applet; it will do so when-
ever it believes that the applet window needs painting.
If the browser window becomes hidden, perhaps because the user dragged
another window in front of it or the user clicked the back button to bring up the
previous page in the browser, the browser immediately calls method:
stop();
of the applet. This method is supposed to stop any computation that it is doing
so that resources are not wasted. When the browser window becomes visible
again, procedure
start
will be called again.
When the browser window is deleted, the browser calls:
destroy();
This procedure is supposed to relinquish any resources that the applet was using.
For example, it could close a file from which it was reading or terminate any dif-
ferent “threads of execution” that it had started.
The use of different resources is outside the scope of this topic. Hence, in
this chapter, we do not discuss methods
start
,
stop
, and
destroy
. Below, we
concentrate on using procedures
paint
and
init
.
Search WWH ::
Custom Search