| The processing of all Web page applets is as follows: |
| 1. The applet's init() method is automatically called when
the page containing the applet is loaded by the browser or applet viewer.
Its purpose is to perform applet initialization and it is called
only once during the life of the applet. For a simple applet, this
is the only required method. An applet does not need a main() method.
If one exists, it is ignored. |
| |
| 2. The applet's start() method is automatically called
after init() and every time the page is revisited. Its purpose
is to resume suspended applet processing when the user
returns to the page after surfing. |
| |
| 3. The applet's stop() method is automatically called
when the user surfs to another page or when the browser is
being shut down. Its purpose is to suspend applet processing. |
| |
| 4. The applet's destroy() method is automatically called
after stop() when the browser or applet viewer is being shut down.
Its purpose is to release all applet resources and it is called
only once during the life of the applet. |
| |
| |
| A sample applet |
| The following statements define a small applet that
displays a message when the user clicks a button. The
button may then be re-clicked to clear the message: |
| |
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Aman extends Applet implements ActionListener
{
Button b = new Button("Show message");
TextField message = new TextField("", 15);
public void init()
{
resize(300, 100);
setBackground(Color.lightGray);
b.addActionListener(this);
add(b);
message.setFont(new Font("Serif", Font.ITALIC, 24));
message.setForeground(Color.red);
message.setEditable(false);
add(message);
}
public void actionPerformed(ActionEvent e)
{
if (message.getText().length() == 0)
{
message.setText("Hello world!");
b.setLabel("Clear message");
}
else {
message.setText("");
b.setLabel("Show message");
}
}
} |
| |
| Notes: |
| 1. By importing the java.applet package, accessing the Applet class is made easier |
| |
| 2. The applet needs no WindowListener interface because it isn't a window |
| |
| 3. Processing begins with the init() method. It immediately
resizes the window to override any size specified by the applet's
HTML tag .Everything else about the applet is virtually the same
as we would see in an equivalent windows program (with the exception
of window event handling which isn't needed). |
| |
| 4. NOTE: The procedure for compiling a Java applet is
identical to the procedure for compiling a Java program.
To test the applet's bytecode, however,we must launch the
applet viewer program. This is
done by entering the command: appletviewer App.php |