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. (In Java 1.2 and later, you can also subclass an applet from the JApplet Swing component.) So creating an applet is more like subclassing a GUI component 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 standard 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 infinite) loops. To perform a time-consuming or repetitive task, such as animation, an applet must create its own thread, over which it does have complete control. The task of writing an applet, then, comes down to defining the appropriate methods. A number of these methods are defined by the Applet class:
In addition to these Applet methods, there are a number of other methods, inherited from superclasses of Applet, that the browser invokes at appropriate times, and which an applet should override. The most obvious of these methods is paint( ) (or paintComponent( ) for Swing-based applets that extend JApplet), which the browser or viewer invokes to ask the applet to draw itself on the screen. A related method is print( ), which an applet should override if it wants to display itself on paper differently than it does on the screen. The Applet class also defines some methods that are commonly used (but not overridden) by applets:
|