Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Creating an Applet 43

run them in any web browser that handles Java programs and 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()blockstatement 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 appletfirst runs. The paint()block is used to display anything that
should be displayed.


To see an applet version of the Rootapplication, 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: importjava.awt.*;
2:
3: public classRootApplet extendsjavax.swing.JApplet {
4: int number;
5:
6: public voidinit() {
7: number= 225;
8: }
9:
10: public voidpaint(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 Rootapplica-
tion. 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.


Applets are slightly more complicated than applications because they must
be able to run on a web page and coexist with other page elements in a
browser. You learn how to create them in Hour 17, “Creating Interactive
Web Programs.”


NOTE
The sample programs in this
hour are provided primarily to
introduce you to the way Java
programs are structured. The
main purpose of this hour is to
get the programs to compile
and see how they function
when you run them. Some
aspects of the programs will be
introduced fully in the hours to
come.
Free download pdf