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);
}

}

This applet version of HelloWorld is a little more complicated than the HelloWorld application of the previous chapter, 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 in the javahtml/classes directory. Compile this file by typing javac HelloWorldApplet.java at the command line prompt.

If all is well a file called HelloWorldApplet.class will be created. This file must be in your classes directory.

Now you need to create an HTML file that will include your applet. The following simple HTML file will do.



Hello World


This is the applet:




Save this file as “HelloWorldApplet.html” in the javahtml directory. When you’ve done that load the HTML file into a Java enabled browser such as HotJava or Netscape 2.0. You should see the following:

This is the applet:
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 the .html file is in the javahtml directory and the compiled .class file is in the javahtml/classes directory.

Comments are closed.