Page Content

Tutorials

What are the 4 Methods of Applet in Java?

Applet in Java

A key component of the early Internet, Java applets provided a dynamic means of delivering interactive information via web browsers. Understanding their functionality and historical background is still essential to understanding Java’s development, even though their popularity has declined, especially as browsers have moved away from plug-ins.

Historical Context

Java was developed to solve two important problems with the Internet: portability and security. With the advent of applets, a new kind of networked program, tiny, self-executing Java applications could be sent over the Internet and executed automatically by a web browser that supported Java. This invention made it possible for some server-side functionality to move to the client, making the web a more dynamic space.

Applet Basics

A Java program that runs in a web browser or specialised applet viewer is called an applet. In contrast to stand-alone Java programs, applets usually don’t need the main() method to run.

Applets are embedded into HTML documents using the <APPLET> tag. The browser or applet viewer then downloads the applet’s bytecode (.class file) to the user’s machine and executes it within a Java Virtual Machine (JVM). For development and testing, the appletviewer tool provided with the Java Development Kit (JDK) is commonly used to run applets without a full browser.

Historically, applets could be built using the Abstract Window Toolkit (AWT), Java’s original GUI framework, or Swing, a more powerful and flexible alternative. Swing applets extend JApplet, which itself inherits from Applet.

Here’s a minimal AWT-based applet example:

Java Code (SimpleApplet.java):

import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=250 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
    public void paint(Graphics g) {
        g.drawString("G'day mate, from an Applet!", 20, 30);
    }
}

To run this, you would save it as SimpleApplet.java, compile it with javac SimpleApplet.java, and then run it using appletviewer SimpleApplet.java.

Code Output (from appletviewer): A small window will appear with the text “G’day mate, from an Applet!” displayed.

Applet Life Cycle Methods

Applets have a unique life cycle that is controlled by a number of essential techniques that the browser or applet viewer automatically calls:

Applet Life Cycle Methods
Applet Life Cycle Methods
  1. public void init(): Following the loading of the applet, the first method called is public void init(). Like a constructor for an application that runs independently, it is used for one-time initialisations.
  2. public void start(): Init() is followed by public void start(), which is also called each time the user returns to the applet’s page. It is used to begin or continue the execution of tasks like operations or animation.
  3. public void stop(): When the user exits the page with the applet, the public void stop() function is called. Since the applet may be restarted later using start(), it is used to halt operations and put it into an idle state.
  4. public void destroy():  Only called when the applet is being fully deleted from memory, usually after the browser closes, is public void destroy(). Its purpose is to release any system like database connections or threads that the applet might still be retaining.
  5. public void paint(Graphics g): This function is used at any time when the output of an AWT-based applet needs to be redone. It is utilised for all visual output and is supplied with a Graphics object that provides the drawing context of the applet. The runtime system is prompted to run paint() by calling repaint() whenever the information presented by an applet changes.

Applet Security Model

Applets employ a “sandbox” security approach, which places stringent restrictions on them to shield the user’s system from malicious software. These limitations consist of:

Applet Security Model
Applet Security Model
  • No local executable code: No executable code on the local computer may be run by applets.
  • Restricted file system access: Applets are unable to write to or read from the local file system.
  • Limited network connections: The applet’s ability to connect to the network is restricted to the host from which it was downloaded.
  • Warning messages: When a window opens from an applet, a warning message will appear to caution users against entering private information.

It is the browser’s SecurityManager that enforces these security measures. The user can offer higher access rights to signed applets while unsigned applets are subject to these stringent restrictions.

Passing Parameters to Applets from HTML

HTML pages can pass information to an embedded applet using <param> tags within the <APPLET> tag. These parameters consist of name and value pairs. Inside the applet, the getParameter(String name) method is used to retrieve the value associated with a given parameter name. The value is always returned as a String, so if the parameter represents a numeric or boolean value, it must be converted to the appropriate data type within the applet. It’s crucial to check for null and handle potential NumberFormatException when parsing these string values.

Here’s an example demonstrating parameter passing:

HTML Code (ParamApplet.html):

<HTML>
<BODY>
<APPLET CODE="ParamApplet.class" WIDTH="300" HEIGHT="100">
    <param name="greetingMessage" value="Kia Ora, World!">
    <param name="fontSize" value="24">
    <param name="fontColour" value="blue">
</APPLET>
</BODY>
</HTML>

Java Code (ParamApplet.java):

import java.awt.*;
import java.applet.*;
/*
<applet code="ParamApplet" width=300 height=100>
<param name=greetingMessage value="Kia Ora, World!">
<param name=fontSize value="24">
<param name=fontColour value="blue">
</applet>
*/
public class ParamApplet extends Applet {
    String message;
    int fontSize;
    Color fontColour;
    public void init() {
        // Retrieve parameters from HTML
        message = getParameter("greetingMessage");
        if (message == null) message = "Hello, Default!";
        String fontSizeParam = getParameter("fontSize");
        try {
            if (fontSizeParam != null)
                fontSize = Integer.parseInt(fontSizeParam);
            else
                fontSize = 12; // Default size
        } catch (NumberFormatException exc) {
            fontSize = 12; // Default on error
        }
        String fontColourParam = getParameter("fontColour");
        if (fontColourParam != null) {
            switch (fontColourParam.toLowerCase()) {
                case "red":    fontColour = Color.red;    break;
                case "green":  fontColour = Color.green;  break;
                case "blue":   fontColour = Color.blue;   break;
                default:       fontColour = Color.black;  break;
            }
        } else {
            fontColour = Color.black;
        }
        setBackground(Color.lightGray);
    }
    public void paint(Graphics g) {
        g.setColor(fontColour);
        g.setFont(new Font("Arial", Font.BOLD, fontSize));
        g.drawString(message, 10, 50);
    }
}

To run this example, save the HTML as ParamApplet.html and the Java code as ParamApplet.java. Compile the Java file, then open ParamApplet.html in a Java-enabled browser or run appletviewer ParamApplet.java.

Code Output (from appletviewer): A window with a light grey background will appear. The text “Kia Ora, World!” will be displayed in blue, with a bold Arial font of size 24.

This thorough review covers all the important facets of Java applets, including their lifetime, security implications, historical relevance, and how they work with HTML for parameter passing.

Index