Adding an Applet to an HTML Document

For many element tag pairs, you can specify an element attribute in the starting tag that defines additional or qualifying data about the element. This is how a Java applet is identified in an tag. Here is an example of how you might include a Java applet in an HTML document:



A Simple Program











The two shaded lines between tags for horizontal lines specify that the byte codes for the applet are contained in the file MyFirstApplet.class. The name of the file containing the byte codes for the applet is specified as the value for the code attribute in the tag. The other two attributes, width and height, define the width and height of the region on the screen that will be used by the applet when it executes. These always have to be specified to run an applet. There are lots of other things you can optionally specify, as we will see. Here is the Java sourcecode for a simple applet:

import javax.swing.JApplet;
import java.awt.Graphics;

public class MyFirstApplet extends JApplet {

public void paint(Graphics g) {
g.drawString("To climb a ladder, start at the bottom rung", 20, 90);
}
}

Note that Java is case sensitive. You can't enter public with a capital P – if you do the program won't compile. This applet will just display a message when you run it. The mechanics of how the message gets displayed are irrelevant here – the example is just to illustrate how an applet goes into an HTML page. If you compile this code and save the previous HTML page specification in the file MyFirstApplet.html in the same directory as the Java applet code, you can run the applet using appletviewer from the JDK with the command:

appletviewer MyFirstApplet.html


We Are Founder..