An Example JApplet

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
Historical topic: Java appletsModern web browsers do not run Java applets. The Applet API was deprecated for removal before Java 25 and was removed in Java 26. Treat applet examples on this page as historical object-oriented/GUI examples; for new desktop interfaces use Swing where appropriate or JavaFX/OpenJFX.

Answer:

No. The Web browser is the main application. An applet is an object that the web browser uses.

An Example JApplet

An applet is an object that is used by another program, typically a Web browser. The Web browser is the application program and (at least conceptually) holds the main() method. The applet part of a Web page provides services (methods) to the browser when the browser asks for them.

An applet object has many instance variables and methods. Most of these are defined in the JApplet class. To access these definitions, your program should import javax.applet.JApplet and java.awt.*. Here is the code for a small applet. The name of the class is Poem and the name of the source file is Poem.java.

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

public class Poem extends JApplet
{
  public void paint ( Graphics gr )
  { 
    setBackground( Color.white );
    gr.drawString("Loveliest of trees, the cherry now", 25, 30);
    gr.drawString("Is hung with bloom along the bough,", 25, 50);
    gr.drawString("And stands about the woodland ride", 25, 70 );
    gr.drawString("Wearing white for Eastertide." ,25, 90);
    gr.drawString("--- A. E. Housman" ,50, 130);
   }
}

The applet is compiled just like an application using javac Poem.java. This produces a bytecode file called Poem.class that can be used in a Web page. Here is what this applet does:

Embedded Java applet removed: modern browsers do not support Java applets. The surrounding source code is retained for historical study.

The applet is responsible for the white rectangle that is part of this page as presented by your Web browser. The size of the rectangle is given in the HTML that describes the entire Web page. This will be discussed later.

Note: If you don't see the white rectangle you may be using a browser that has applets disabled. Sometimes this is done for security reasons. Also, some firewalls block applets.

QUESTION 2:

Look at the code for the class Poem. How many methods does it define?