JAVA Applet

You may have choosen to write your program in Java. Here is an example of changing a java program into java applet that can be run directly on browsers.

Applications and applets start program execution in different ways; an application has a main() method and an applet has a init() method inititiated by the browser.

// tell the compiler where to find the methods you will use.
// required when you create an applet
import java.applet.*;
// required to paint on screen
import java.awt.*;

// the start of an applet - HelloWorld will be the executable class
// Extends applet means that you will build the code on the standard Applet class
public class HelloWorld extends Applet
{
// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
}

// This method gets called when the applet is terminated
// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
}

// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.
public void paint(Graphics g)
{
//method to draw text on screen
// String first, then x and y coordinate.
g.drawString("Hello World!",20,40);
}

}

Compile the .java file in command line:

javac HelloWorld.java

Then it is ready to be embed it into a html file. Two HTML tags are used to specify a java applet.

The <APPLET> tag basically just tells the browser what applet.class file to use, and how wide and high the applet should be. There are additional (optional) attributes you can set up, too; but in simplest use, that's all there is to this tag, and usually all you will need.

The <PARAM> tag names a parameter fir the JAVA applet, and provides the VALUE for it. Note that calling different applets may require different number of PARAM tags according to the number of arguments required by the applet. Here's the framework of a simple HTML tag set for putting an applet into your page:

<APPLET CODE="filename.class" WIDTH="400" HEIGHT="200">
< param name = parameter1 value = "value1" >
< param name = parameter2 value = "value2">
< param name = parameter3 value = "value3">
< param name = parameter4 value = "value4">
</APPLET>

Here is the example HTML we use to call the hello world applet. Since the applet does not expect any parameters, there is no PARAM field within the APPLET tags.

<html>
<head>
<title> Hello World </title>
</head>

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

The CODE="filename.class" contains the name of the applet's class file. The class file is a small executable which does the real work of the applet. You have to put it under the same directory as the HTML page calling it, or you have to use CODEBASE attribute to specify the directory.

Click here to see it working