Programming and Problem Solving with Java

(やまだぃちぅ) #1
14.2 H o w D o Y o u W r i t e a n Applet? | 661

In Chapter 8, you learned how to create GUIs using the swing
package. Swing is a GUI toolkit provided as a core part of the Java
2 platform. It is not a new set of tools, but rather an enhancement
of the AWT toolkit that was used on previous platforms. Many of
the Swing classes that you used in Chapter 8 have the letter “J” in
front of them: JButton,JLabel, and JTextField. The “J” distinguishes
the class from the AWT class of the same name. Both AWT and
Swing support applets. Figure 14.1 shows the inheritance hier-
archy. As you can see, the JAppletclass is derived from Applet.
In our applications, we had to instantiate a JFrameinto whose
content pane we added our user interface components. Because
an applet is itself a container, we simply call methods such as add
and setLayoutdirectly. Thus writing applets is easier than writ-
ing applications with frames.


14.2 How Do You Write an Applet?


We demonstrate how to write an applet through the use of two
previous examples. The first is the factorial function, which orig-
inally did not use a GUI, and the second is the calculator appli-
cation, which did use such an interface.


Factorial


Let’s consider how to write an applet in the context of a specific problem. In Chapter 13, we
wrote the factorial function. What we didn’t mention there is that the factorial of a number
becomes very large very fast. Let’s write an applet that lets us enter a number and then dis-
plays the factorial of that number. This process continues until the user closes the window
in the browser. Thus an event loop is set up, allowing the user to continue to enter a value
for which the factorial is computed.
We display the code for the applet and intersperse discussion of this code at the differ-
ent parts. Note that we are removing the “J” from in front of the class names of the window
components. That is, we are presenting AWT applets rather than Swing applets. The reason
for doing so is that many older browsers are not set up to accept Swing applets, and those
that are can still run AWT applets.


// Applet FactInt on file FactInt.java computes the factorial of
// its input and stores it in a variable of type int, which is
// displayed on the screen.


importjava.applet.Applet;
importjava.awt.; // Supplies user interface classes
importjava.awt.event.
; // Supplies event classes


AWT

Swing

Object

Component

Container

Panel

Applet

JApplet

Figure 14.1 Applet Inheritance Hierarchy for AWT
and Swing
Free download pdf