An applet is a Java program that runs on a webpage. Applets function like regular Java programs but with a few security restrictions (such as applets can't read or write files on your computer).
This tutorial focuses on:
- The Applet class
- Applet class methods
- Building an applet
- Placing an applet on a webpage
- Viewing an applet
The Applet class
The Applet class is used to create applets. This class is located in the java.applet package. Applets are not created by instantiating an Applet object, rather by creating a class which extends the Applet class.
Applet class methods
- init() - Initializes an applet for usage and informs the applet that it has been loaded
- start() - Informs an applet that it should start its execution
- stop() - Informs an applet that it should stop its execution
- destroy() - Informs an applet that it is being removed from memory and any resources it has allocated should be removed as well
- resize(int width, int height) - Resizes the applet to the specified width and height
Building an applet
The first four methods discussed above are actually run by a web browser automatically. You can define the functionality of these methods in your applet code to specify what happens during each stage of an applet's existence.
The applet below uses these methods to print to a textarea what is currently happening.
Placing an applet on a webpage
Now that you have a ready applet. Let's place it on a webpage. This can be done using HTML's <applet> tag.
Here is the applet:
If the applet doesn't load, try viewing this page in a different web browser.
NOTE: You should always refer to the compiled program file (the one with the .class extension) in an <applet> tag when placing an applet on a webpage. Not the .java source code file!
Viewing an applet
You can view an applet by viewing the webpage on to which the applet is placed in a web browser or you can use the Java appletviewer command line tool. In the command prompt type appletviewer and the name of the page where the applet is located.
The appletviewer will display just the applet, not the entire webpage.