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 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.