Applets

Contents

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

Prerequisites

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:

init()

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

start()

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.

stop()

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

destroy()

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

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

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

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 MyHelloWorld.java -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");
    myPanel.add(myButton);
      myPanel.add(myTextField);
    Container myContentPane = getContentPane();
    myContentPane.add(myPanel,"Center");

  }

}

The HTML document

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

 

 

 

 

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