Professional Documents
Culture Documents
Chapter 13
Chapter Preview
Java is a ne programming language, yet it is not for that
alone that it has generated so mu
h ex
itement, but for its
potential role in animating the World Wide Web. In this
hapter we dis
uss the meaning of that role, and begin to
show how you
an animate your own small part of the web
by writing applets in Java. We rst introdu
e Java graphi
al
omponents, in
luding text elds, buttons, and s
roll bars,
and we show how Java programs
an be made to rea
t to
users' a
tions upon those
omponents. By doing this, we will
no longer have to rely on the CSLib pa
kage to write graph-
i
al programs. We further show how the Java appli
ations
that we've written
an be run from within web browsers.
The fundamental things apply,
As time goes by.
|Herman Huupfeld
\As Time Goes By"
was used only in the optional Chapter 11. We'll use many more of their
lasses in this
hapter. But most of all, we will use another pa
kage,
javax.swing. The
lasses in this pa
kage are used to
reate all sorts
of stu that one normally asso
iates with graphi
al user interfa
es- graphi
al user interfa
es
(GUIs): buttons, menus, text areas, s
roll bars, and so on. Ea
h of
omponents
these items,
alled
omponents, has an asso
iated
lass. The pa
kage
java.awt.event
ontains
lasses that allow us to intera
t with the
graphi
al
omponents, just as it
ontained
lasses allowing us to
at
h
mouse events.
There are two important
omponents that we have already seen
indire
tly { the Frame and the Dialog
omponents. Our CSLib's
DrawingBox and OutputBox are really variants of Frame, while our
InputBox and ErrorBox are variants of Dialog.
Until now, we have relied on the DrawingBox
lass from the CSLib
pa
kage for writing graphi
al programs. However, real Java graphi
al
programs require mu
h more powerful pa
kages and
lasses. The
lass
that we will use in pla
e of our DrawingBox is Java's JFrame
lass.
JFrame is very similar to Frame (see bug alert ??).
Remember the J.
In this
hapter, we are
overing the so-
alled Swing
om-
ponents, whi
h in
lude JFrame, JButton, JS
rollBar, and
many others.
Why the \J"? There is another set of
omponents in
java.awt itself, with names Frame, Button, et
. These
om-
ponents | the \abstra
t windowing toolkit," or \AWT,"
omponents | were introdu
ed rst and took the good
names. The later Swing
omponents had to use dierent
names, so the J was added.
Some of the dieren
es between the AWT
omponents and
the Swing
omponents are dis
ussed in se
tion ?? of this
hapter. The important thing to know now is that you should
use only the Swing
omponents in your programs | mixing
AWT and Swing
omponents is asking for trouble. So, don't
forget the J!
By the way, you may wonder why we import java.awt in our
programs if we are not going to use AWT
omponents. As
with almost everything related to
omputers, there are ex
ep-
tions to the above rule: o
asionally, AWT
omponents must
be used. We will point these out as we pro
eed. Further,
java.awt
ontains numerous useful
lasses that are not
om-
ponents, su
h as Color, Font, and Point. We will
ontinue
to use those
lasses.
Bug Alert 13.1
4 CHAPTER 13. JAVA SWING (OPTIONAL)
1 Using the Swing
omponents is a bit more
ompli
ated than using CSLib. That is, of
ourse, exa
tly why we wrote CSLib!
13.1. THE JAVA SWING COMPONENTS 5
1 import javax.swing.*;
2 import java.awt.*;
3
4 publi
lass TwoButtons {
5 JFrame f;
6 JButton redButton, blueButton;
7
8 publi
TwoButtons () {
9 f = new JFrame("Two Buttons Frame");
10 redButton = new JButton("Red");
11 blueButton = new JButton("Blue");
12 Container
p = f.getContentPane();
13
p.setLayout(new FlowLayout());
14
p.add(redButton);
15
p.add(blueButton);
16 f.setSize(150, 70);
17 f.setVisible(true);
18 }
19 }
We
ould obtain a perfe
t size for the JFrame by doing the kinds
of experiments that you did in the last qui
k exer
ise. But there is an
elegant way to adjust the size of a
ontainer to be just large enough
to a
ommodate its
ontained
omponents, without guesswork. Ev-
ery
omponent has a preferred size. By sending to a JFrame the preferred size
pa
k() message, it will be resized to be just large enough to hold pa
k()
all of its
omponents set to their preferred sizes. In addition to meth-
6 CHAPTER 13. JAVA SWING (OPTIONAL)
To see how resizing the window works, run the above pro-
gram with the setSize
all omitted; then with the size set
to 50 by 50; then with the size set to 50 by 100. As another
experiment, omit the setLayout
all; the results here will be
surprising; we will explain them in se
tion ??.
Qui
k Exer
ise 13.1
ods for setting and getting a Component's a
tual size, there are methods
setPreferredSize(...) and getPreferredSize(...) for manipulat-
ing a Component's preferred size. For a JButton, the default preferred
size is just large enough to
ontain the JButton's label. Here's a
om-
plete appli
ation in
orporating these
on
epts.
1 import javax.swing.*;
2 import java.awt.*;
3
4 publi
lass TwoButtons {
5 JFrame f;
6 JButton redButton, blueButton;
7
8 publi
TwoButtons () {
9 f = new JFrame("Two Buttons Frame");
10 redButton = new JButton("Red");
11 blueButton = new JButton("Blue");
12 Container
p = f.getContentPane();
13
p.setLayout(new FlowLayout());
14
p.add(redButton);
15
p.add(blueButton);
16 f.pa
k();
17 f.setVisible(true);
18 }
19 }
Methods of the JButton
lass are given in Table 13.1; the JComponent
lass, from whi
h it inherits, is do
umented in Table 13.2. Many of
these methods serve to
hange the appearan
e of the button: its
olor,
font, and so on. These methods are also dened for other
omponent
lasses, so we
an illustrate them with JButton.
foreground
olor A button has a foreground
olor used for the text itself and a
ba
kground
olor ba
kground
olor used for the rest of the button. The Color
lass in
java.awt has
onstants Color.red, Color.blue, et
.
The Font
lass in java.awt
an be used to
reate font obje
ts,
whi
h
an then be used to render the text in a
omponent by sending
font family the
omponent the setFont message. \Helveti
a" is the name of a font
typefa
e family or typefa
e, whi
h in
ludes
hara
ters with a
ommon look in
various sizes and styles (su
h as itali
and bold). \Courier" is another
typefa
e.
This version of TwoButtons draws the text of the buttons in red
Helveti
a and blue Courier, respe
tively, on a gray ba
kground:
1 import javax.swing.*;
2 import java.awt.*;
3
4 publi
lass TwoButtons {
5 JFrame f;
6 JButton redButton, blueButton;
7
8 publi
TwoButtons () {
9 f = new JFrame("Two Buttons Frame");
13.1. THE JAVA SWING COMPONENTS 9
10
11 redButton = new JButton("Red");
12 redButton.setForeground(Color.red);
13 redButton.setBa
kground(Color.gray);
14 redButton.setFont(new Font("Helveti
a", Font.PLAIN, 14));
15
16 blueButton = new JButton("Blue");
17 blueButton.setForeground(Color.blue);
18 blueButton.setBa
kground(Color.gray);
19 blueButton.setFont(new Font("Courier", Font.BOLD, 18));
20
21 Container
p = f.getContentPane();
22
p.setLayout(new FlowLayout());
23
p.add(redButton);
24
p.add(blueButton);
25 f.pa
k();
26 f.setVisible(true);
27 }
28 }
In line 14, we ask for the plain style of Helveti
a in size 14 (
alled
point\14 points," a point being a length used by typographers, equal to
approximately 721 of an in
h). In line 19, we ask for the bold style of
Courier in 18-point size. The Font
lass is summarized in Table 13.3.
i
on The label on a button
an in
lude a small image |
alled an i
on
| instead of, or in addition to, the text. An i
on is any obje
t of a
lass
that implements the I
on interfa
e, shown in Figure 13.4. One su
h
lass, provided in the Swing pa
kage, is ImageI
on. (Note that this
name does not start with a J; even though it is in the Swing pa
kage,
13.1. THE JAVA SWING COMPONENTS 11
Method Purpose
void paintI
on(Component
, Graphi
s g, draw i
on at lo
ation (x,y).
int x, int y)
int getI
onWidth() return i
on's width, in pixels.
int getI
onHeight() return i
on's width, in pixels.
it does not
ompete with any name in the AWT pa
kage, so the J is
not needed.) Its
onstru
tor
ImageI
on (String filename)
10
11 ImageI
on leftarrow = new ImageI
on("left1.gif");
12 leftButton = new JButton(leftarrow);
13 leftButton.setBorder(null);
14
15 ImageI
on rightarrow = new ImageI
on("right1.gif");
16 rightButton = new JButton(rightarrow);
17 rightButton.setBorder(null);
18
19 Container
p = f.getContentPane();
20
p.setLayout(new FlowLayout());
21
p.add(leftButton);
22
p.add(rightButton);
23 f.pa
k();
24 f.setVisible(true);
25 }
26 }
right3.gif:
We
an make these the \rolled over" and \pressed" i
ons for the
two buttons:
1 import javax.swing.*;
2 import java.awt.*;
3
4 publi
lass TwoButtons {
5 JFrame f;
6 JButton leftButton, rightButton;
7
8 publi
TwoButtons () {
9 f = new JFrame("Two Buttons Frame");
10
11 ImageI
on leftarrow = new ImageI
on("left1.gif");
12 leftButton = new JButton(leftarrow);
13 leftButton.setBorder(null);
14 ImageI
on leftarrowdown = new ImageI
on("left2.gif");
15 leftButton.setPressedI
on(leftarrowdown);
16 ImageI
on leftarrowover = new ImageI
on("left3.gif");
17 leftButton.setRolloverI
on(leftarrowover);
18 leftButton.setRolloverEnabled(true);
19
20 ImageI
on rightarrow = new ImageI
on("right1.gif");
21 rightButton = new JButton(rightarrow);
22 rightButton.setBorder(null);
23 ImageI
on rightarrowdown = new ImageI
on("right2.gif");
24 rightButton.setPressedI
on(rightarrowdown);
14 CHAPTER 13. JAVA SWING (OPTIONAL)
Method Purpose
void a
tionPerformed (A
tionEvent e)
alled when any a
tion event o
urs
Rea
tive
omponents work very similarly to the mouse events that we
saw in Chapter 11. The major dieren
e is that the mouse is not
aÆliated with any on-s
reen artifa
t, whereas buttons are.
To in
lude a rea
tive JButton in a program, the basi
steps are:
1. Import the java.awt.event pa
kage.
2. In the
lass heading, the program de
lares itself to implement
the A
tionListener interfa
e. The A
tionListener interfa
e is
shown in Table 13.5.
3. Typi
ally in the
onstru
tor, on
e the JButton has been
reated,
\this" obje
t registers itself as being interested in listening for
events from the JButton.
4. The one method of the A
tionListener interfa
e (namely
a
tionPerformed) is dened. The A
tionEvent argument
an
be used to nd out more about the event. The method
a
tionPerformed is invoked when the event (a button press) o
-
urs.
These steps are summarized in Figure 13.3.
On
e again, a UML
lass diagram is useful for illustrating the as-
so
iations between
lasses. The UML diagram for the skeletal
ode of
Figure 13.3 is shown in Figure 13.4. The UML generalization and
omposition asso
iations are just as they were for the se
ond ver-
sion of TwoButtons. But this time, we in
lude additional information
about Java events. We see that JButton has a \generates" asso
ia-
tion with A
tonEvents; the A
tionEvents in turn are \listened for"
by the
lassname. Finally, in order for
lassname to be able to ful-
ll its role as an event listener, it must implement the Java interfa
e
A
tionListener. A UML notation for a Java interfa
e is indi
ated by
UML implements itali
izing the interfa
e name; the implements asso
iation is indi
ated
asso
iation by a dashed line with a
losed, unlled arrowhead at the abstra
t
lass
end. We
ould have just an
hored the tail of this \implements" as-
so
iation at the edge of
lassname. But here we
an provide just a
little more information|we group the methods of
lassname, and an-
hor the tail of the \implements" asso
iation near the method(s) that
13.3. THE JAVA AWT EVENT MODEL 17
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
:::
JButton buttonname;
:::
publi
lassname () f
:::
Container
p = getContentPane();
p.add( buttonname);
:::
buttonname.addA
tionListener(this);
:::
:::
g
g
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4
5 publi
lass ButtonInt extends JFrame
6 implements A
tionListener {
7
8 JButton intButton;
9 int
ount = 0; // our
ounter
10
11 publi
ButtonInt () {
12 super("Button Counter");
13 intButton = new JButton("" +
ount);
14
15 intButton.addA
tionListener(this);
16
17 Container
p = getContentPane();
18
p.setLayout(new FlowLayout());
19
p.add(intButton);
20
21 pa
k();
22 setVisible(true);
23 }
24
25 publi
void a
tionPerformed (A
tionEvent e) {
26
ount++;
27 intButton.setText("" +
ount);
28 }
29 }
This same idea works for other
omponents, but the details may
vary. For example, some
omponents are registered as ItemListeners
instead of A
tionListeners, using the method addItemListener in-
stead of addA
tionListener. Another
ompli
ating fa
tor is that
a program may
ontain more than one rea
tive
omponent, and
a
tionPerformed needs to know whi
h one to rea
t to. We will address
these issues shortly.
You may have noti
ed (espe
ially if you've been doing the Qui
k Ex-
er
ises) that when running the TwoButtons program not all of the
standard buttons on the frame work. The minimize and maximize but-
tons work ne, but the \
lose window" button does not. It
loses the
window, but it doesn't terminate the program. The reason for this is
that the Java implementation of JFrame is
apable of generating various
WindowEvents su
h as the
losing of the window, the i
oni
ation of WindowEvents
the window, et
. (See Table 13.6.). Some of these events
ause a
hange
in the appearan
e of the window { su
h as i
oni
ation/dei
oni
ation.
But others
ause no spe
ial
hange in the window's appearan
e, and
have no other asso
iated a
tion { it is ne
essary for the programmer to
provide listeners if there is to be any a
tion taken.
If we want our program to listen for the window
losing event,
we must implement the WindowListener interfa
e, and its seven re- WindowListener
quired methods. These are summarized in Table 13.7. Of
ourse, we
ould do this dire
tly in the
lasses themselves. But writing
ode for
losing a window is done so often that we usually dene a new
lass,
say ClosableJFrame, that extends Java's JFrame. Then instead of
TwoButtons extending JFrame, we have it extend ClosableJFrame.
20 CHAPTER 13. JAVA SWING (OPTIONAL)
Method Purpose
void windowOpened (WindowEvent e)
alled when a window is opened
void windowClosing (WindowEvent e)
alled when a window is being
losed
void windowClosed (WindowEvent e)
alled when a window has been
losed
void windowI
onified (WindowEvent e)
alled when a window is i
onied
void windowDei
onified (WindowEvent e)
alled when a window is dei
onied
void windowA
tivated (WindowEvent e)
alled when a window is a
tivated
void windowDea
tivated (WindowEvent e)
alled when a window is dea
tivated
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4
5 publi
lass ClosableJFrame extends JFrame implements WindowListener {
6
7 publi
ClosableJFrame () {
8 this("");
9 }
10
11 publi
ClosableJFrame (String title) {
12 super(title);
13 addWindowListener(this);
14 }
15
16 publi
void windowClosing (WindowEvent e) {
17 dispose();
18 System.exit(0);
19 }
20 publi
void windowA
tivated (WindowEvent e) {}
21 publi
void windowClosed (WindowEvent e) {}
22 publi
void windowOpened (WindowEvent e) {}
23 publi
void windowDea
tivated (WindowEvent e) {}
24 publi
void windowDei
onified (WindowEvent e) {}
25 publi
void windowI
onified (WindowEvent e) {}
26
27 }
TABLE 13.8: Some
onstants and methods of the JLabel
lass. Other
methods are inherited from JComponent.
Our next example shows the use of labels and text elds. Re
all the
temperature
onversion program from Se
tion ?? on page ??. We'll
rewrite that program to take its input from a JTextField, and to
produ
e its output in a JLabel, with ea
h
omponent pla
ed in the
JFrame.
Our program,
alled TempConversion,
reates a JTextField in
whi
h to enter a number; that number is interpreted as a number of
degrees on the Fahrenheit s
ale, and its equivalent on the Centigrade
s
ale is displayed. The program is shown in Figure 13.7, and a snapshot
of the program's output is shown in Figure 13.8.
The rst few lines are just as in the prototype in Figure 13.3.
We have the usual import statements, the extends ClosableJFrame
lause, the implements A
tionListener
lause, the
onstru
tor, and
the required method a
tionPerformed.
Noti
e how, in lines 10 and 11, we have de
lared the obje
ts tFahr
and lCent. The reason for the strange looking names is that we have
used a
onvention for naming variables that refer to
omponents, in
whi
h the rst letter tells something about the nature of the
omponent.
In these
ases, the leading t tells us that tFahr refers to a text eld,
and the leading l tells us that lCent refers to a label. As with other
naming
onventions, this is merely a suggestion that sometimes helps
us remember what a variable means. You might imagine that, without
some sort of naming
onvention, we might use the name labelCent on
one day, outputCent on another, and
entMessage on yet another. In
graphi
al programs, variables that refer to
omponents (su
h as lCent
and tFahr) are usually instan
e variables, so that they
an be initialized
by the
onstru
tor, and a
essed by listeners and other methods.
24 CHAPTER 13. JAVA SWING (OPTIONAL)
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4
5 publi
lass Temperature extends ClosableJFrame
6 implements A
tionListener {
7 // Convert from Fahrenheit to Centigrade
8 // Author: Jennifer Mi
kunas, August 23, 2002
9
10 JTextField tFahr;
11 JLabel lPrompt, lCent;
12
13 publi
Temperature () {
14
15 // Set the title and the layout manager
16 super("Temperature Conversion");
17 Container
p = getContentPane();
18
p.setLayout(new FlowLayout());
19
20 // Create the TextField and the Label
21 tFahr = new JTextField(10);
22 lCent = new JLabel("I'll tell you what that is in degrees C");
23 lPrompt = new JLabel("Please type the temperature (deg F): ");
24
25 // Lay out the three Components
26
p.add(lPrompt);
27
p.add(tFahr);
28
p.add(lCent);
29 pa
k();
30 setVisible(true);
31
32 // Register the Component Listener
33 tFahr.addA
tionListener(this);
34 }
35
36 // Respond to A
tion Event: typing in the tFahr TextField
37 publi
void a
tionPerformed (A
tionEvent e) {
38 double fahr=0.0,
39
ent=0.0;
40 fahr = Integer.parseInt(tFahr.getText());
41
ent = 5.0 * (fahr - 32) / 9.0;
42 lCent.setText(fahr + " deg F is " +
ent + " deg C");
43 pa
k();
44 }
45 }
To show how to deal with multiple rea
tive
omponents we'll extend
the Fahrenheit to Centigrade temperature
onversion program. This
time, we will write the program so that it
an
overt temperatures
in either dire
tion. Instead of one input text eld, we will have two.
Depending on whi
h one the user utilizes for input, the program will
ompute the appropriate
onverted temperature and display it in the
other text eld (using setText|see Table 13.9). The program is
1 import javax.swing.*;
2 import java.awt.*;
13.6. MULTIPLE REACTIVE COMPONENTS 27
3 import java.awt.event.*;
4
5 publi
lass Temperature extends ClosableJFrame
6 implements A
tionListener {
7
8 // Convert temperature from/to Fahrenheit/Centigrade
9 // Author: Peter Baranowi
z, September 10, 2000
10
11 JTextField tFahr = new JTextField(9),
12 tCent = new JTextField(9);
13
14 publi
Temperature () {
15 super("Two Way Conversion");
16
17 // Lay out the Components.
18 Container
p = getContentPane();
19
p.setLayout(new FlowLayout());
20
p.add(new JLabel("Fahrenheit"));
21
p.add(tFahr);
22
p.add(new JLabel("Centigrade"));
23
p.add(tCent);
24 pa
k();
25 setVisible(true);
26
27 // Register Component Listeners
28 tFahr.addA
tionListener(this);
29 tCent.addA
tionListener(this);
30 }
31
32 publi
void a
tionPerformed (A
tionEvent e) {
33 // Respond to A
tion Events:
34 // 1. tFahr TextField
35 // 2. tCent TextField
36 double fahr,
ent;
37
38 if (e.getSour
e()==tFahr) {
39 fahr = Double.parseDouble(tFahr.getText());
40
ent = 5.0 * (fahr - 32.0) / 9.0;
41 tCent.setText(
ent + "");
42 }
43 else {
44
ent = Double.parseDouble(tCent.getText());
45 fahr = 9.0 *
ent / 5.0 + 32.0;
46 tFahr.setText(fahr + "");
47 }
48 }
49 }
28 CHAPTER 13. JAVA SWING (OPTIONAL)
There are many
omponent
lasses in Swing. The JChe
kBox and the
similar JRadioButton are simple rea
tive
omponents that are very
mu
h like buttons, ex
ept in one way: instead of generating \a
tion
events," they generate \item events." The
on
ept is the same, but the
details are dierent.
30 CHAPTER 13. JAVA SWING (OPTIONAL)
JChe
kBoxes typi
ally are used to sele
t one or more items. For exam-
ple, if you were ordering a
ar, you might
he
k \power brakes" and
\power steering" but omit \air
onditioning."
JChe
kBox powerBrakes = new JChe
kBox("Power Brakes");
JChe
kBox powerSteering = new JChe
kBox("Power Steering");
JChe
kBox airConditioning = new JChe
kBox("Air Conditioning");
...
p.add(powerBrakes);
p.add(powerSteering);
p.add(airConditioning);
:::
publi
lassname () f
:::
Container
p = getContentPane();
p.add( boxname);
:::
boxname.addItemListener(this);
:::
:::
g
g
Method Purpose
void itemStateChanged (ItemEvent e)
alled when any item event o
urs
initially sele
ted. Our
ode registers \this" program as the listener for
all four of the
omponents (lines 47 through 50).
Within the itemStateChanged method (lines 53 through 58), we
ould
he
k to see whi
h JRadioButton triggered the ItemEvent in the
same way that we
he
ked for JTextField events. However, the only
thing that we really need to do is
all the private method
ompute,
where all of the real work is done. Likewise, in the a
tionPerformed
method (lines 60 through 65), we just
all the
ompute method.
Within
ompute, we rst read the input from both the tHeight
and the tWeight JTextField, and
ompute bodyMassIndex (lines 68
through 69). Then we determine whi
h of the gender RadioButtons is
sele
ted in line 71. Note that line 71 is just a
leaner way of writing
if (gender.getSele
tion() == femaleChe
k)
female = true;
else
female = false;
What would the output of the Body Mass program look like
if we had not expli
itly set the frame size to 250 200? What
would it have looked like if instead we had done a pa
k()?
Qui
k Exer
ise 13.7
38 CHAPTER 13. JAVA SWING (OPTIONAL)
when required. This is a
onsequen
e of the Layout Manager, whi
h Layout Manager
governs how
omponents are arranged when they are added to a frame.
In our programs so far in this
hapter, we used the FlowLayout layout
manager.
The Java API denes several layout manager
lasses. To
hange
the layout manager used by a graphi
al frame, send the message
setLayout( layout-manager-obje
t);
to the frame. In the remaining programs of this
hapter, we will use
three layout managers:
FlowLayout. If the frame's layout manager is set to be an obje
t of
this
lass,
setLayout(new FlowLayout());
then the frame will arrange the
omponents a
ording to the order
in whi
h they were added (by add), going left to right and top to
bottom, as we have seen.
BorderLayout. When this type of layout is used,
setLayout(new BorderLayout());
the frame is divided into north, south, east, west, and
enter areas,
as shown in Figure 13.12. Components are added to the frame
with a spe
ial two-argument add method. For example,
add(new JLabel("The Title"), BorderLayout.NORTH);
divides the frame into a grid with three rows and ve
olumns;
it is an error to add more than 15
omponents, but if fewer are
added the leftover pla
es in the grid will be left empty. All
ells
of the grid have the same dimensions.
40 CHAPTER 13. JAVA SWING (OPTIONAL)
70 // 1. femaleRadio RadioButton
71 // 2. maleRadio RadioButton
72
ompute();
73 }
74
75 publi
void a
tionPerformed (A
tionEvent e) {
76 // Respond to A
tion Events:
77 // 1. tHeight TextField
78 // 2. tWeight TextField
79
ompute();
80 }
81
82 private void
ompute () {
83 double height = new Double(tHeight.getText()).doubleValue();
84 double weight = new Double(tWeight.getText()).doubleValue();
85 double bodyMassIndex = weight / (height * height);
86 boolean female = femaleChe
k.isSele
ted();
87
88 lIndex.setText("Your body-mass-index is " + bodyMassIndex);
89 if ((bodyMassIndex > 27.8) ||
90 (female && (bodyMassIndex > 27.3)))
91 lHigh.setText("This is
onsidered high.");
92 else
93 lHigh.setText("This is not
onsidered high.");
94 pa
k();
95 }
96 }
You
annot tell by the gray s
ale pi
ture, but the \January 2000"
banner is red on a yellow ba
kground, and the body of the
alendar is
blue on gray. By examining the desired s
reen appearan
e, you may be
able to dedu
e what kinds of JPanels and layouts we use. The names
that we give to the various
omponents are
1. banner
ontains the name of the month and the year.
2. sele
t
ontains the JS
rollBar.
3. days is a JPanel
ontaining the days of the week.
4. pBody is a JPanel
ontaining the body of the
alendar.
Before reading further, see if you
an gure out our layout plan.
We use the BorderLayout manager (the one with "NORTH",
"SOUTH", "EAST", "WEST" and "CENTER" panes, shown in Figure 13.12).
For our
alendar, the north strip will
ontain the banner, the sele
t,
and the days
omponents; the
enter portion will
ontain the body
of the
alendar. The remaining border positions will not be used, so
they will have zero size. The north strip is another JPanel with a
3 1 GridLayout; within this JPanel, the banner
omponent will be
on line 1, the sele
t
omponent on line 2, and the days
omponent
on line 3. The days
omponent is yet another JPanel with a 1 7
GridLayout, ea
h
ell
ontaining a JLabel telling the day of the week.
In the
enter position we pla
e a Panel that uses a 6 7 GridLayout,
putting a JLabel into ea
h
ell.
46 CHAPTER 13. JAVA SWING (OPTIONAL)
Method Purpose
void adjustmentValueChanged (AdjustmentEvent e)
alled when any adjustment event
o
urs
First, the
onstru
tor (lines 23 through 80) is where the work of
setting up the frame layout takes pla
e. In the
onstru
tor, we
1. Determine the month, year for today's date (lines 26 through
29).
2. Compute tallyMonth (line 31) for the s
rollbar.
3. Instantiate the banner JLabel, and set its alignment, font, and
foreground
olor (lines 34 through 38).
13.9. A CALENDAR PROGRAM 51
import javax.swing.*;
import java.awt.*;
1 import javax.swing.*;
2 import java.awt.*;
3
4 publi
lass Clo
k extends JPanel {
5
6 int hour,
7 minute;
8
9 publi
Clo
k () {
10 this(12,0);
11 }
12
13 publi
Clo
k (int hour, int minute) {
14 set(hour, minute);
15 }
16
17 publi
void set (int hour, int minute) {
18 int totalMinutes = (hour * 60 + minute) % (12 * 60);
19 // totalMinutes is between -(12 * 60) and (12 * 60)
20 if (totalMinutes < 0) totalMinutes = totalMinutes + (12 * 60);
21 this.hour = totalMinutes / 60;
22 if (this.hour == 0) this.hour = 12;
23 this.minute = totalMinutes % 60;
24 }
25
26 publi
int getHour () { return hour; }
27 publi
int getMinute () { return minute; }
28
29 // Draw a
lo
k in this panel.
30 publi
void paintComponent (Graphi
s g) {
31
32 super.paintComponent(g);
33
34 int w = getWidth()-1,
35 h = getHeight()-1;
36 int x = w/2,
37 y = h/2; //
enter at (x,y)
38 int r = Math.min(x, y); // radius
39
40 // Draw the
lo
k in bla
k.
41 g.setColor(Color.bla
k);
42 g.drawOval(x-r, y-r, 2*r, 2*r);
43
44 // Set the
olor to blue for the hands
45 g.setColor(Color.blue);
46 // Draw the minute hand.
47 drawHand(g, x, y, r, minute/60.0);
48
49 // Draw the hour hand.
13.10. CUSTOM DRAWING IN SWING 55
sent to a JLabel. But how does the run-time system know when a
omponent needs to be redrawn? In our Clo
k
lass, whenever the
hour or minute is
hanged, the
lo
k should be redrawn, but how
ould
the run-time system possibly know this? In fa
t, it doesn't. That is
why, whenever the time is
hanged in a
tionPerformed, we must ask
the system to redraw the
lo
k by
alling repaint.
Most readers of this book are familiar with the World Wide Web. You
use it whenever you use a web browser, su
h as Nets
ape Communi
ator
or Mi
rosoft's Internet Explorer. Browsers allow you to view home home pages
pages (also
alled web pages) set up by other users on other
omputers web pages
that are on the web. These home pages
ontain text and images and,
less frequently, sound and animation. The
omputer that provides the
home page is
alled a server (or http server, for hypertext transport server
proto
ol server); your
omputer is the
lient (although, at the same
lient
time, it may be a server for other
lients). Ea
h home page has an
address, giving the server it is on and its lo
ation on that server. This
address is
alled a uniform resour
e lo
ator (URL). uniform resour
e
Home pages are written in a
omputer language
alled hypertext lo
ator
markup language (HTML), a language very dierent from Java. HTML hypertext markup
pages are typed into a le, like Java programs. They are not
ompiled, language
but when a
omputer on the web requests an HTML do
ument, it
re
eives the text in the le and uses it to
reate the image that the
browser displays. In Se
tion 13.11.1, we provide a qui
k HTML primer,
enough for you to
reate a simple home page with text and images.
For the most part, when you view a web page in a browser, it is
stati
|that is, it does not move mu
h. There are limited ex
eptions,
but something as dynami
as, for example, a video game
ould not be
written as an HTML do
ument. Simply put, HTML do
uments
annot
exploit the
omputing power of the
lient. Java applets
an over
ome
this limitation of web pages. Later in this
hapter, we show how to
write applets and in
lude them in your own web pages.
13.11.1 HTML
1 <HTML>
2 <HEAD>
3 <TITLE> My first home page </TITLE>
4 </HEAD>
5 <BODY>
6
7 My name is Napoleon I, Emperor of Fran
e.
8 I'm just learning HTML, so please be patient.
9 Soon, I will have the greatest home page in the
10 entire
ivilized world.
11
12 </BODY>
13 </HTML>
3 GIF stands for graphi
s inter
hange format; JPEG stands for joint photographi
experts
group.
4 You
an nd lots of small images like these by surng the net. When an image shows up
in the web page you are viewing, your browser will allow you to save your own
opy of it;
he
k the do
umentation for the browser.
60 CHAPTER 13. JAVA SWING (OPTIONAL)
9 <H1>Napoleon I</H1>
10 </CENTER>
11
12 <P>
13 <IMG SRC="images/greyline.gif">
14
15 <P>
16 My name is Napoleon I, Emperor of Fran
e.
17 I am a famous general and have
onquered many
ountries.
18 I am most proud of my work at Austerlitz, and have always
19 felt that my generalship at Waterloo has been underestimated.
20
21 <P>
22 In my spare time, I like to do origami
23 and spend quiet evenings at home with my wife Josephine.
24 </BODY>
25 </HTML>
4 </HEAD>
5 <BODY>
6
7 <CENTER>
8 <IMG SRC="images/me.jpg">
9 <H1>Napoleon I</H1>
10 </CENTER>
11
12 <P>
13 <IMG SRC="images/greyline.gif">
14
15 <P>
16 My name is Napoleon I, Emperor of Fran
e.
17 I am a famous general and have
onquered many
ountries.
18 I am most proud of my work at Austerlitz, and have always
19 felt that my generalship at Waterloo has been underestimated.
20
21 <P>
22 In my spare time, I like to do
23 <A HREF=
24 "http://www.yahoo.
om/Re
reation/Hobbies_and_Crafts/Origami/">
25 origami</A>
26 and spend quiet evenings at home with my wife
13.11. JAVA AND THE WEB 63
27 <A HREF="jojo.html">Josephine</A>.
28 </BODY>
29 </HTML>
You
an
reate your own simple home page using just the HTML
features we presented. For it really to be a web page, you must pla
e
it on an http server with an appropriate name and in an appropriate
dire
tory; ask your system administrator how to do this.
The features we have
overed allow the
reation of only \stati
"
web pages. You may have seen a
tive-looking web pages|for example,
those with animated GIFs or forms and sear
h fa
ilities|but HTML
provides very limited fa
ilities for su
h a
tive pages. The purpose of
Java is to remedy this.
Imagine you would like to provide a simple video game on the Internet.
You are willing to do all the work and provide the game for free. In
fa
t, you will provide it to anyone who
an a
ess your home page.
But how? You might provide it as an exe
utable le; but then users
have to download and store it and then exit their browsers to run it.
Furthermore, many will be unwilling to try it for fear of viruses. The
best solution would be to provide it as part of your home page, but
there is no way to write the game in HTML.
Here is where Java
omes in. It
an be used to write applets,
omputer programs that run within a window of your home page set
aside for the applet. The browser
an guarantee that the applet
annot
store unwanted data on your ma
hine and does not
arry a virus. With
a applet (or several!) running in your home page, it is truly an a
tive
page.
Fortunately, all of the programs that we have written so far
an be
transformed into applets! More pre
isely, we
an write a \shell" applet
that allo
ates an instan
e of any of the programs we have written so
far. On
e your applet shell is written and
ompiled into a .
lass le,
you must write some HTML to in
lude it in your web page. In your
web page you use the <APPLET> tag to open a window for the applet
and start it up.
<APPLET CODE=" lename.
lass",
WIDTH= integer,
HEIGHT= integer>
</APPLET>
The <APPLET> tag gives the name of the
lass le as the CODE attribute,
and the size of the applet's window as the WIDTH and HEIGHT attributes.
The HTML page in Figure 13.21 in
ludes the \BodyMass" program as
an applet, whi
h we will now explain. Noti
e that the Java program
64 CHAPTER 13. JAVA SWING (OPTIONAL)
1 <HTML>
2 <HEAD>
3 <TITLE> Emperor Napoleon's Home Page </TITLE>
4 </HEAD>
5 <BODY>
6
7 <CENTER>
8 <IMG SRC="images/me.jpg">
9 <H1>Napoleon I</H1>
10 </CENTER>
11
12 <P>
13 <IMG SRC="images/greyline.gif">
14
15 <P>
16 My name is Napoleon I, Emperor of Fran
e.
17 I am a famous general and have
onquered many
ountries.
18 I am most proud of my work at Austerlitz, and have always
19 felt that my generalship at Waterloo has been underestimated.
20
21 <P>
22 In my spare time, I like to do
23 <A HREF=
24 "http://www.yahoo.
om/Re
reation/Hobbies_and_Crafts/Origami/">
25 origami</A>
26 and spend quiet evenings at home with my wife
27 <A HREF="jojo.html">Josephine</A>.
28
29 <P>
30 Also, I am just learning to write applets!
31 Here is my first effort; I hope you like it:
32
33 <APPLET CODE="BodyMassApplet.
lass" WIDTH=0 HEIGHT=0>
34 </APPLET>
35
36 </BODY>
37 </HTML>
must spe
ify the full le name for the program's .
lass le, en
losed
in double quotes. The size of the applet is set to 0 0 in line 33 be
ause
we do not pla
e anything expli
itly in the browser window; we just run
the BodyMass program, whi
h pops up its own frame.
The Java shell for an applet always has a parti
ular form, as fol-
lows:
1 import javax.swing.*;
2 import java.applet.*;
3
4 publi
lass BodyMassApplet extends JApplet {
5
6 publi
void init () {
7 new BodyMass();
8 }
9 }
78
79 private void
ompute () {
80 double height = Double.parseDouble(tHeight.getText());
81 double weight = Double.parseDouble(tWeight.getText());
82 double bodyMassIndex = weight / (height * height);
83 boolean female = femaleRadio.isSele
ted();
84
85 lIndex.setText("Your body-mass-index is " + bodyMassIndex);
86 if ((bodyMassIndex > 27.8) ||
87 (female && (bodyMassIndex > 27.3)))
88 lHigh.setText("This is
onsidered high.");
89 else
90 lHigh.setText("This is not
onsidered high.");
91 }
92 }
We mentioned in bug alert 13.1 that the java.awt pa
kage has a set of
omponents analogous to Swing
omponents, su
h as Frame, Button,
and TextField. Moreover, the
lasses in the Swing pa
kage are des
en-
dants of AWT
lasses | spe
i
ally, the Swing
omponents are des
en-
dants of JComponent, whi
h is a sub
lass of java.awt.Container. The
AWT pa
kage pre
eded the Swing pa
kage by several years, and is still
heavily used, although Swing is mu
h more powerful. What exa
tly is
the
onne
tion between the two pa
kages?
The essential distin
tion between these sets of
omponents is
ap-
tured by the terms heavyweight
omponent and lightweight
omponent. lightweight
heavyweight
To understand these terms, we must step ba
k a bit further and dis
uss
omponent
how
omponents are implemented.
Every Java program runs on a
omputer that is equipped with
an operating system (OS). The operating systems in widest use are operating system
Mi
rosoft's Windows, Apple's Ma
OS, and, from various vendors, Unix;
ea
h has numerous versions. There are many other operating systems
with smaller user bases. For the purposes of this dis
ussion, we
an
think of an OS as providing two servi
es:
1. The OS is an intermediary between the programs running on the
omputer and the I/O devi
es
onne
ted to it. The running pro-
70 CHAPTER 13. JAVA SWING (OPTIONAL)
5 The prin
ipal ex
eption is JFrame, whi
h must
all the OS to reserve spa
e on the s
reen.
Summary 71
Summary
Graphi
al programs
an be written in Java without using our
CSLib, but instead using the Java APIs dire
tly. The most important
pa
kages for this purpose are javax.swing (the Swing API), java.awt
(the Abstra
t Windowing Toolkit), and java.awt.event (the event
model, whi
h we rst used in Chapter 11).
72 CHAPTER 13. JAVA SWING (OPTIONAL)
MyApp () {
Container
p = getContentPane();
...
reate
omponents ...
p.add(
omponent1);
p.add(
omponent2);
...
setVisible(true);
}
Most
omponents are rea
tive, meaning that the program needs to
take some a
tion when the
omponent is
li
ked or has text typed into
it. The AWT event model | to whi
h we were already introdu
ed in
Chapter 11 | is used for su
h
omponents. The pro
edure for making
omponents rea
t varies slightly among
omponents, but always follows
a similar pattern. For example, to
reate a button that responds to
being
li
ked, your program would have the form
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
JButton b;
MyApp () {
Container
p = getContentPane();
b = new JButton("button label");
p.add(b);
...
b.addA
tionListener(this);
setVisible(true);
}
Exer ises
e f