Java Reference
In-Depth Information
TIP: Ending a Swing Program
A GUI program is normally based on a kind of infinite loop. There may not be a Java
loop statement in a GUI program, but nonetheless the GUI program need not ever
end. The windowing system normally stays on the screen until the user indicates that
it should go away (for example, by clicking the "Click to end program." button in
Display 17.2). If the user never asks the windowing system to go away, it will never
go away. When you write a Swing GUI program, you need to use System.exit to
end the program when the user (or something else) says it is time to end the pro-
gram. Unlike the kinds of programs we saw before this chapter, a Swing program will
not end after it has executed all the code in the program. A Swing program does not
end until it executes a System.exit . (In some cases, the System.exit may be in some
library code and need not be explicitly given in your code.)
System.exit
Self-Test Exercises
7. What kind of event is fired when you click a JButton ?
8. What method heading must be implemented in a class that implements the
ActionListener interface?
9. Change the program in Display 17.2 so that the window displayed has the title "My
First Window" . Hint: Consult the description of constructors in Display 17.3.
EXAMPLE: A Better Version of Our First Swing GUI
Display 17.4 is a rewriting of the demonstration program in Display 17.2 that
includes a few added features. This new version produces a window that is similar to
the one produced by the program in Display 17.2. However, this new version is done
in the style you should follow in writing your own GUIs. Notice that the window is
produced by defining a class ( FirstWindow ) whose objects are windows of the kind we
want. The window is then displayed by a program ( DemoWindow ) that uses the class
FirstWindow .
Observe that FirstWindow is a derived class of the class JFrame . This is the normal
way to define a windowing interface. The base class JFrame gives some basic window
facilities, and then the derived class adds whatever additional features you want in your
window interface.
Note that the constructor in Display 17.4 starts by calling the constructor for the
parent class JFrame with the line
super ();
(continued)
Search WWH ::




Custom Search