Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Workshop: Creating an Applet

When the Java language was introduced, the language feature that got the most attention was applets, Java programs that run on web pages. You can run them on web pages in any web browser that handles Java programs, such as Microsoft Internet Explorer or Mozilla Firefox. You also can test them with appletviewer, a tool included in the JDK that's supported in NetBeans.

The structure of applets differs from applications. Unlike applications, applets do not have a main() block. Instead, they have several sections that are handled depending on what is happening in the applet. Two sections are the init() block statement and the paint() block. init() is short for initialization, and it is used to take care of anything that needs to be set up as an applet first runs. The paint() block is used to display anything that should be displayed.

To see an applet version of the Root application, create a new empty Java file with the class name RootApplet. Enter the code in Listing 4.3 and make sure to save it when you're done.

Listing 4.3. The Full Text of RootApplet.java

 1: import java.awt.*;
 3: public class RootApplet extends javax.swing.JApplet {
 4:     int number;
 6:     public void init() {
 7:         number = 225;
 8:     }
10:     public void paint(Graphics screen) {
11:        Graphics2D screen2D = (Graphics2D) screen;
12:        screen2D.drawString("The square root of " +
13:            number +
14:            " is " +
15:            Math.sqrt(number), 5, 50);
16:     }
17: }

This program contains many of the same statements as the Root application. The primary difference is in how it is organized—the main() block has been replaced with an init() block and a paint() block.

When you run the program in NetBeans (choose Run, Run File), the applet loads in the appletviewer tool, as shown in Figure 4.2.

Figure 4.2

Figure 4.2 The applet running in .

  • + Share This
  • 🔖 Save To Your Account