Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

236 HOUR 17:Creating Interactive Web Programs


Applicationsbegin running with the first statement inside the main()
block. There is no main()method in a Java applet, so there’s no set starting
place for the program. Instead, an applet has a group of standard methods
that are handled in response to specific events as the applet runs.
The following are the events that could prompt one of the applet methods
to be handled:

. The program is loaded for the first time, which causes the applet’s
init()and start()methods to be called.
. Something happens that requires the applet window to be redis-
played, which causes the applet’s paint()method to be called.
. The program is stopped by the browser, which calls the applet’s
stop()method.
. The program restarts after a stop, which calls start().
. The program is unloaded as it finishes running, which calls
destroy().


The following is an example of a bare-bones applet:
public classSkeleton extendsjavax.swing.JApplet {
// program will go here
}

Appletclass files must be publicbecause the JAppletclass also is public.
(If your applet uses other class files of your own creation, they do not have
to be declared public.)
Your applet’s class inherits all the methods that are handled automatically
when needed: init(), paint(), start(), stop(), and destroy().
However, none of these methods do anything. If you want something to
happen, you must override these methods with new versions in your
applet.

Painting an Applet Window
The paint()method is used to display text and graphics within the applet
window. Whenever something needs to be displayed or redisplayed in the
applet, the paint()method handles the task. You also can force paint()to
be called by using the followingstatement in an applet:
repaint();
Free download pdf