Java Reference
In-Depth Information
Self-Test Exercises
1. When you define a class and make it implement the
WindowListener
interface,
what methods must you define? What do you do if there is no particular action
that you want one of these methods to take?
2. The GUI in Display 18.2 has a main window. When the user clicks the close-
window button in the main window, a smaller window appears that says
"Are you
sure you want to exit?"
What happens if the user clicks the close-window but-
ton in this smaller window? Explain your answer.
3. If you want a Swing program to end completely, you can invoke the method
System.exit
. What if you want a
JFrame
window to go away, but you do not
want the program to end? What method can you have the
JFrame
invoke?
4. Rewrite the class in Display 18.2 so that the class is its own window listener.
Hint:
The constructor will contain
addWindowListener(
this
);
18.2
Icons and Scroll Bars
I
ICONS
.
Bumper sticker
Icons
JLabel
s,
JButton
s, and
JMenuItem
s can have icons. An
icon
is simply a small picture,
although it is not required to be small. The label, button, or menu item may have just
a string displayed on it, just an icon, or both (or it can have nothing at all on it). An
icon is an instance of the
ImageIcon
class and is based on a digital picture file. The pic-
ture file can be in almost any standard format, such as
.gif
,
.jpg
, or
.tiff
.
The class
ImageIcon
is used to convert a picture file to a Swing icon. For example, if
you have a picture in a file named
duke_waving.gif
, the following will produce an
icon named
dukeWavingIcon
for the picture
duke_waving.gif
:
icon
ImageIcon
ImageIcon dukeIcon =
new
ImageIcon("duke_waving.gif");
The file
duke_waving.gif
should be in the same directory as the class in which this
code appears. Alternatively, you can use a complete or relative path name to specify the
picture file. Note that the picture file is given as a value of type
String
that names the
picture file. The file
duke_waving.gif
and other picture files we will use in this chapter
are all provided on the CD that accompanies this text.