Life cycle of an applet
Example 1 - A simple applet
Example 2 - A simple Swing applet


To run an apllet in a browser you need to have the Java Virtual machine and the Java Plug-in installed. Both can be downloaded from the Sun homepage.


Life cycle of an applet

The four methods which gives the framework top buiklt an applet:


Works much like a constructor and is automatically called when when the applet is launched. Use the method for intializations.


This method is automatically called after Java has called the init method. It is also called whenever the user returns to the page containing the applet. This mean that this method can be repeatedly.


This method is automatically called when the suer moves off thepage where the applet sits.


Called when the browser shuts down.


Example 1 - A simple Applet

This apllet simply displays the text: This is a message from the MyHelloWorld Applet ! in the browser. The applet and the html page must be located in the same directory.

The MyHelloWorld class

import java.applet.Applet;
import java.awt.Graphics;

public class MyHelloWorld extends Applet {
    public void paint(Graphics g) {
        g.drawString("This is a message from the MyHelloWorld applet !", 50, 25);

The HTML document

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<TITLE> A Simple Program </TITLE>

Here is the output of my program:
<APPLET CODE="MyHelloWorld.class" WIDTH=400 HEIGHT=150> 

Compiling the applet

The applet is compiled the same way as other Java programs. E.g. if the MyHelloWorld java is located in the D:\javatest directory it is compiled this way from the DOS prompt:

D:\javatest>javac -classpath d:\javatest

Example 2 - A simple Swing applet

Example that shows how to display a button and a textfield in an applet.

Note: This exampole requires at least Java 2 v1.4.0

The ButtonApplet Class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonApplet extends JApplet
{ public void init()
  { JPanel myPanel = new JPanel();
    JButton myButton = new JButton("Push me");
    JTextField myTextField = new JTextField("This is a textfield");
    Container myContentPane = getContentPane();



The HTML document

<h1>Button Applet</h1>
<applet code="ButtonApplet.class" width="850" height="500">





Converted from CHM to HTML with chm2web Standard 2.7 (unicode)