FAQ 3a
Updated: 1/19/00
>>>>>> How do I make an Applet?
==================================
You must create a class that extends the Applet class.
The class file should be placed in a '*.java' file with the same name:
// 'MyApplet.java' code file
import java.applet.*;
class MyApplet extends Applet {}
>>>>>> How does an Applet work?
===============================
Applets come with baggage. There are a number of functions that already
exist inside an applet that you need to overwrite.
The most important functions are the constructor (same name as the class),
init(), and paint() functions. Other functions let you respond to the users
actions. See FAQ_3b, FAQ_3c, and FAQ_3f.
// 'MyApplet.java' code file
import java.applet.*;
import java.awt.*;
class MyApplet extends Applet {
String name;
String eyes;
MyApplet(){ // constructor
name = "Fred";
}
public void init(){ // called during initialization
eyes = "Blue";
}
public void paint(Graphics g){
Rectangle r = getBounds(); // applet boundaries, drawing size
g.setColor(Color.yellow);
g.fillRect(r.left,r.top,r.width,r.height);
g.setColor(new Color(128,0,128));
g.drawString("My Name is "+name,10,20);
g.drawString("My Eyes are "+eyes,10,40);
}
}
As you can see, the constructor and init() both set the class values.
The difference is that the 'applet' object does not exist during
construction, but does exist during initialization. This is a
subtle point, but can be important later on.
If you want to learn more about the 'Graphics' class, go find 'Graphics.java'
and look at all the functions available. The Graphics object in paint() draws
directly to the applet screen. This example will fill the screen with yellow,
then draw two messages in a dark purple color.
>>>>>> How do I put an Applet into my Web Page?
===============================================
You place the following type of line into your web page:
<applet code="MyApplet.class" width=100 height=100>
</applet>
Code is the name of your applet class.
Width and Height are the size of the applet on your web-page.
Another important value is Codebase. If your applet class is NOT
in the same folder with the web-page, then codebase tells your web-page
where to find the applet:
<applet code="MyApplet.class" codebase="/myCodeDirectory" width=100 height=100>
</applet>
If you do it right, the result looks like this:
(HINT: do a 'view source' to see how I added this applet)