Hello World: The Applet

The reason people are excited about Java as more than just another OOP language is because it allows them to write interactive applets on the web. Hello World isn't a very interactive program, but let's look at a webbed version.

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

              
public class HelloWorldApplet extends Applet {

  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
  
} 

The applet version of HelloWorld is a little more complicated than the HelloWorld application, and it will take a little more effort to run it as well.

First type in the source code and save it into file called HelloWorldApplet.java. Compile this file in the usual way. If all is well a file called HelloWorldApplet.class will be created. Now you need to create an HTML file that will include your applet. The following simple HTML file will do.

<html>
<head>
<title> hello world </title>
</head>

<body>
This is the applet:<P>
<applet code="HelloWorldApplet" width="150" height="50">
</applet>
</body>
</html>

Save this file as HelloWorldApplet.html in the same directory as the HelloWorldApplet.class file. When you've done that, load the HTML file into a Java enabled browser. You should see something like below, though of course the exact details depend on which browser you use.

Hello World!

If the applet compiled without error and produced a HelloWorldApplet.class file, and yet you don't see the string "Hello World" in your browser chances are that the .class file is in the wrong place. Make sure HelloWorldApplet.class is in the same directory as HelloWorld.html. Also make sure that your browsers supports Java or that the Java plugin has been installed. Not all browsers support Java out of the box.

Many browsers have less than perfect support for Java so if you have trouble with an applet, the first thing to try is loading it into Sun's Applet Viewer instead. If the Applet Viewer has a problem, then chances are pretty good the problem is with the applet and not with the browser.


Previous | Next | Top | Cafe au Lait

Copyright 1997-8, 2004, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 1, 2005