Intro to JavaApplet and Display (Draw) Text

A Java applet is a small application which is written in Java and delivered to users in the form of bytecode. The user launches the Java applet from a web page, and the applet is then executed within a Java Virtual Machine (JVM) in a process separate from the web browser itself. A Java applet can appear in a frame of the web page, a new application window, Sun's AppletViewer, or a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language, which was released in 1995. Wikipedia

Life Cycle of an Applet:

  • init: This method is intended for whatever initialization is needed for an applet.
  • start: This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages.
  • stop: This method is automatically called whenever the user moves away from the page containing applets. This method can be used to stop an animation.
  • destroy: This method is only called when the browser shuts down normally.

Every Applet needs to implement one or more of the init(), the start( ) and the paint( ) methods.

See the HelloWorld sample below.


import java.applet.*;
import java.awt.*;

// Applet code for the "Hello, world!" example.
// This should be saved in a file named as "".
public class HelloWorld extends Applet {

    // Print a message on the screen (x=20, y=10).
    public void paint(Graphics g) {
        g.drawString("Hello, world!", 20, 10);

After compilation, the resulting .class file can be placed on a web server and invoked within an HTML page by using an <applet> or an <object> tag. For example:

<applet code="HelloWorld.class" height="40" width="200">