JAVATM MASTER

My First Applet

Back to Table of Contents

Here is the code to make this bare bones simple Applet just for demonstrating the very basics.

This text is displayed if your browser cannot support Applets.

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

public class MyFirstApplet extends Applet{

	public void init(){
		setBackground(Color.yellow);
		add(new Label("Hello World!"));
		add(new Label("I am an Applet"));
	}

}
The HTML code for this Applet is as follows:

<applet code="MyFirstApplet.class"
width="150" height="70">
This text is displayed if your browser cannot support Applets.
</applet>

Explanation: This compiled JavaTM class runs on the built in Java Virtual Machine of your browser or operating system. The yellow color is set by a static field in the java.awt.Color Object called yellow set to the background of the Applet.

Note: in Swing, JApplet is a little more complex -- you don't just add Labels to the JApplet, as is the case for Applet. In JApplet you add Components to its ContentPane with a call to getContentPane().

Also, JApplets, being composed of Swing classes, generally must use a java plugin, unless you are using Mac OS X with a browser that takes advantage of the built in JVM. Orgininally to use a java plugin, one had to convert the Applet tags in the HTML page to The appropriate tags, using a HTML Converter that can be downloaded freely from http://java.sun.com. However, the Java 1.4+ plugin is automatically invoked when a browser comes across the <applet>...</applet> Tags for most browsers.

The Width and Height values in the Applet tag tell the browser how large to make the Applet. The code Attribute refers to your main class, which here is 'MyFirstApplet.class', and this must extend Applet. Note that JApplet also extends Applet, so a JApplet is another Applet, the Swing version, and it bahaves somewhat differently, though still an Applet.

Moving on, take a look at a more advanced Applet that uses threads: My Threaded Applet

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*