COMPONENTS OF AN APPLETS
An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of any applet that is to be embedded in a Web page. The Applet class provides a standard interface between applets and their environment. (Source: Java Documentation)
Applets are different than normal programs. Because they are viewed in a web browser, they do not require a main function to launch the program.
All applet programs you create will extend the Applet class. This means that your class will inherit all the Applet class’s functionality.
There are two methods that you need to work with. The first method is init(). It is automatically executed when the applet is loaded. The only way to have it run again is by closing your browser and restarting it. The second method is paint(Graphics g). It is automatically called anytime the window has to be redrawn.
Important: Both methods are automatically called by your browser/operating system. You will not manually call them yourself.
Here is their general structure:
//import statements go
here
public class AppletName
extends Applet
{
//optional data fields go here
public void init()
{
}
public void paint( Graphics g )
{
}
}
B) DATA FIELDS
If you have data that you need to store so that it is available each time the paint method is called, then you need to store that data in data fields. These data fields should be initially set in the init function.
Common data fields could be the width and height of the applet. You will see this in the example below.
C) THE init METHOD
This method is where you will initialize your data fields. You can also set your background colour here. Other possibilities include set the font and the drawing colour.
This method is where you will place all your drawing commands. This method is used by your browser or operating system when the applet’s window is moved, enlarge, brought to focus, …
Click here to see the code for the HiMom Applet.