Java Reference
In-Depth Information
The Panel now is complete, with 16 buttons added to create a keypad. The
Panel is a composite component , or a container with added components. The
act of adding the Panel to the Frame will add all the buttons at once. Later in the
program, a call to the actionPerformed() method will determine what action will
take place when a user clicks any one of the 16 buttons.
Coding the addWindowListener() Method
Figure 6-20 displays the code to add a WindowListener for the Frame. Java's
addWindowListener() method in line 120 registers the listener with the Frame.
As you learned in Chapter 5, when you register a listener with a Frame, you con-
nect two objects so that events from one object, the Frame, are sent to the other
object, the listener. The listener tells the Frame object to listen for such events
and respond accordingly.
120
addWindowListener (
121
new WindowAdapter ()
122
{
123
public void windowClosing ( WindowEvent e )
124
{
125
System .exit ( 0 ) ;
126
}
127
}
128
) ;
129
130
} // end of constructor method
131
FIGURE 6-20
The argument inside the parentheses for the addWindowListener —
which extends through line 128, where you see the closing parenthesis and
the semicolon — creates a new instance of the WindowAdapter class. The
WindowAdapter class provides the window event-handling methods discussed in
Chapter 5.
In lines 123 through 126, the program overrides the windowClosing()
method, telling the program to terminate and close the window when the user
clicks the Close button in the Frame. If the program is not terminated in this
manner, it will continue to run.
The following step enters the code for the addWindowListener() method.
To Code the windowClosing() Method
1. Enter lines 120 through 131 as shown in Figure 6-20.
The TextPad window displays the code for the addWindowListener() method
(Figure 6-21). The addWindowListener() method creates an occurrence
of the WindowAdapter class. Lines 123 through 126 override the
windowClosing() method, so that clicking the title bar Close button
terminates the program.
Search WWH ::




Custom Search