How do I change an applet background color?

By default the applet will usually have a grey background when displayed in a web browser. If you want to change it then you can call the setBackground(java.awt.Color) method and choose the color you want. Defining the background color in the init() method will change the color as soon as the applet initialized.

package org.kodejava.example.applet;

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

public class BackgroundColorApplet extends Applet {
    public void init() {
        // Here we change the default grey color background of an 
        // applet to yellow background.
        setBackground(Color.YELLOW);
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.drawString("Applet background example", 0, 50);
    }
}

How do I read an applet parameters?

package org.kodejava.example.applet;

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

public class AppletParameterExample extends Applet {
    private String name = "";

    public void init() {
        // Here we read a parameter named name from the applet tag definition
        // in our html file.
        name = getParameter("name");
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.drawString("Hello " + name + ", Welcome to the Applet World.", 0, 0);
    }
}

Now we have the applet code ready. To enable the web browser to execute the applet create the following html page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>Parameterized Applet</title>
</head>
<body>
    <applet code="org.kodejava.example.applet.AppletParameterExample" 
            height="150" width="350">
        <param name="name" value="Mr. Bean" />
    </applet>
</body>
</html>

How do I create a Hello World Applet?

The code below demonstrate the very basic of Java applet. Applet is a small Java application that can be embedded on the web browser.

package org.kodejava.example.applet;

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {
    public void init() {
    }

    public void start() {
    }

    public void stop() {
    }

    public void destroy() {
    }

    public void paint(Graphics g) {
        g.setColor(Color.GREEN);
        g.drawString("Hello World", 50, 100);
    }
}

To display the applet we need to create an HTML document. Here is a simple example of the document.

<html>
<head>
    <title>Hello World Applet</title>
</head>

<body>
    <applet 
        code="org.kodejava.example.applet.HelloWorldApplet" 
        height="250" 
        width="250">
    </applet>
</body>
</html>

You can now load the applet in your browser or by using the appletviewer utility.