Description of Code
We will examine the code line by line. The following code needs to
be saved in a file called Lesson1.java.
// file: Lesson1.java
// type: Java source
// note: A first applet in Java
// author: Gregory C. Walsh
// date: 3.9.1999
import java.applet.Applet;
import java.awt.*;
public class Lesson1 extends Applet {
public void paint(Graphics g) {
g.drawString("Your first Java Applet!", 20, 30);
}
}
The first few lies are single line comments. The two import statements
are similar to include statements in a C program - they allow us
to draw upon the prewritten class Applet in java/applet
and also every class in the directory java/awt/
.
There is no preprocessor in Java, unlike C! We intend to
use methods and classes defined in both directories.
The first line of the code defines a public class Lesson1. Note that this
class etends Applet, so it inherits all of class Applets methods and
data. This is good because making an applet is actually really
complicated, and many functions and data re required. We don't
really care about these functions for this applet, so inheriting
them from a generic applet is fine. We only care about one
function, the paint function.
The paint function of the Applet is called whenever the window needs to
be drawn. The data of the picture and its associated functions are wrapped
up together in an object of the type Graphics. The paint function is
passed a reference to this object when it is called so it may access
and change this data. We of course will use function provided by the
Graphics object to figure out which pixels to set what color.
To compile this code, we need to first tap java
if we are on a Unix box or open an Console window (MSDOS) on
a PC and set up the PATH variable so the tools can be found (see
jpath.bat on the turtorial page). To run this applet, we need
an html file with the following like embedded in it:
< applet code="Lesson1.class" width=200 height=50 > </applet>
My version of the applet