Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data like clipboard or file system. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applet’s user interface.
A Java applet extends the class
java.applet.Applet, or in the case of a Swing applet,
javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (
Applet) is a descendant of
Panel which is a descendant of
Container. As applet inherits from container, it has largely the same user interface possibilities as an ordinary Java application, including regions with user specific visualization.
The first implementations involved downloading an applet class by class. While classes are small files, there are frequently a lot of them, so applets got a reputation as slow loading components. However, since jars were introduced, an applet is usually delivered as a single file that has a size similar to a large image file (hundreds of kilobytes to several megabytes).
Applet class provides a framework for applet execution, defining methods that the system calls when milestones occur. Milestones are major events in an applet’s life cycle. Most applets override some or all of these methods to respond appropriately to milestones.
init method is useful for one-time initialization that doesn’t take very long. The
init method typically contains the code that you would normally put into a constructor. The reason applets don’t usually have constructors is that they aren’t guaranteed to have a full environment until their
init method is called. Keep the
init method short so that your applet can load quickly.
Every applet that performs tasks after initialization (except in direct response to user actions) must override the
start method. The
start method starts the execution of the applet. It is good practice to return quickly from the
start method. If you need to perform computationally intensive operations it might be better to start a new thread for this purpose.
Most applets that override the
start should also override the
stop method. The
stop method should suspend the applet’s execution, so that it doesn’t take up system resources when the user isn’t viewing the applet’s page. For example, an applet that displays an animation should stop trying to draw the animation when the user isn’t viewing it.
Many applets don’t need to override the
destroy method because their
stop method (which is called before
destroy) will perform all tasks necessary to shut down the applet’s execution. However, the
destroy method is available for applets that need to release additional resources.