- Applet - a special kind of Java program which is automatically run as part of a web page
displayed in a browser. However, the code for an applet is very similar to the code for any graphical
Java program.
- Applet is actually a pre-defined Java class in the java.applet package (using AWT). The new,
Swing version of applets is JApplet, so we'll use the JApplet class, which is in the
javax.swing package. We'll learn more about inheritance later, but to write our own applet, we write
a new class which inherits from JApplet. That's the meaning of the code extends JApplet
- Instead of a main method, Applets run their paint method when they are displayed. This method
has access to a Graphics object, which is what it uses for its display.
- To display text using a Graphics object, we use the drawString method.
- Putting all of the above together, we get our first applet:
import java.awt.Graphics;
import javax.swing.JApplet;
public class HelloApplet extends JApplet {
public void paint(Graphics g) {
super.paint(g);
g.drawString("Hello World!", 20, 30); // display at position (20,30)
}
}
- To run an applet, we must write a web page which references it using an applet tag such as the
following:
<applet code="HelloApplet.class" width = 400 height = 50></applet>
- The above applet tag is included below, so you should see the above applet running right here:
- Of course, to make the above applet work, I compiled the file HelloApplet.java, and copied the
object file HelloApplet.class into the same directory as this document on my web site. I also set the
permission for the class file so that everyone can read it (using "chmod a+r HelloApplet.class").
- Applets are set up as graphical applications, so it's easy to do things such as drawing shapes with
methods such as setColor and drawOval:
g.setColor(Color.blue); // use the pre-defined blue color
g.drawOval(20, 30, 100, 50);
- Adding the above lines to my applet produces the following: