A Simple Applet Example - Hello World!

The easiest example to begin with is the Hello World example. There are two files that must be present in the same directory - example.html and HelloWorld.class. Once again - You need to have a web page in which to run an applet. The code in the HTML page called example.html should be something like:

 1 
 2 
 3   <title> Test Applet Page </title>
 4   <body>
 5     <applet code=HelloWorld.class width=200 height=200>
 6     </applet>1
 7   </body>
 8  
 9 
1

The <APPLET> tag is the only tag we are concerned with. The other tags are standard HTML.

The code in the Applet HelloWorld.java should look like:

 1 
 2 
 3   // The HelloWorld Applet - Displays Hello World! 
 4   // at the pixel location (20,20)
 5   
 6   import java.awt.Graphics;1
 7   import java.applet.Applet;
 8 
 9   public class HelloWorld extends Applet2
10   {	
11     public void paint(Graphics g)3
12     {
13       g.drawString("Hello World!",20,20);4
14     }
15   }
16   
17 
1

The packages (libraries) to include.

2

Applet is the parent class.

3

The paint() method is responsible for drawing to the screen.

4

Draws the String object "Hello World!" to the (20,20) screen location.

First off, remember the code must be compiled by typing javac HelloWorld.java and this will create a file called HelloWorld.class in the same directory. The Applet is viewed by using appletviewer tool that is run by typing: appletviewer example.html

The appletviewer creates a web browser area for the applet to run in, which then loads the HelloWorld class and allows it to run in the appletviewer window. We will discuss this code next.