Java Reference
In-Depth Information
Self-Test Exercises
(continued)
41. What would happen if the user running the GUI in Display 17.19 were to
type the number
10
into the text fi eld and then click the addition button three
times? Explain your answer.
42. Suppose you change the
main
method in Display 17.19 to the following:
public static void
main(String[] args)
{
Calculator calculator1 =
new
Calculator();
calculator1.setVisible(
true
);
Calculator calculator2 =
new
Calculator();
calculator2.setVisible(
true
);
}
This will cause two calculator windows to be displayed. (If one is on top of the
other, you can use your mouse to move the top one.) If you add numbers in
one of these calculators, will anything change in the other calculator?
43. Suppose you change the
main
method in Display 17.19 as we described in
Self-Test Exercise 42. This will cause two calculator windows to be displayed.
If you click the close-window button in one of the windows, will one window
go away or will both windows go away?
Chapter Summary
•
Swing GUIs (graphical user interfaces) are programmed using event-driven program-
ming. In event-driven programming, a user action, such as a button click, generates
an event, which is automatically passed to an event-handling method that performs
the appropriate action.
•
There are two main techniques for designing a Swing GUI class. You can use inheri-
tance to create a derived class of one of the library classes such as
JFrame
or you can
build a GUI by adding components to a container class. You normally use both of
these techniques when defining a Swing GUI class.
•
A
windowing GUI
is usually defined as a derived class of the class
JFrame
.
•
A
button
is an object of the class
JButton
. Clicking a button fires an action event
that is handled by an action listener. An
action listener
is any class that implements
the
ActionListener
interface.
•
A
label
is an object of the class
JLabel
. You can use a label to add text to a GUI.
•
When adding components to an object of a container class, such as adding a but-
ton to a panel or
JFrame
, use the method
add
. The components in a container are
arranged by an object called a
layout manager
.