Java Reference
In-Depth Information
Figure 14-5. WindowListener, WindowAdapter, and my WindowCloser
Let's put this all together in some code examples. Class WindowDemo2 puts up a JFrame and
closes when you ask it to. The online source includes the older AWT Frame-based Win-
dowDemo .
public
public class
class WindowDemo2
WindowDemo2 extends
extends JFrame {
public
public static
void main ( String [] argv ) {
JFrame f = new
static void
new WindowDemo2 ();
f . setVisible ( true
true );
}
public
public WindowDemo2 () {
setSize ( 200 , 100 );
setDefaultCloseOperation ( WindowConstants . DO_NOTHING_ON_CLOSE );
addWindowListener ( new
new WindowDemoAdapter ());
}
/** Named Inner class that closes a Window. */
class
class WindowDemoAdapter
WindowDemoAdapter extends
extends WindowAdapter {
public
public void
void windowClosing ( WindowEvent e ) {
// whimsy - close randomly, ~ 1 times in 3
iif ( Math . random () > 0.666 ) {
System . out . println ( "Goodbye!" );
WindowDemo2 . this . setVisible ( false
false );
// window will close
WindowDemo2 . this . dispose ();
// and be freed up.
System . exit ( 0 );
}
System . out . println ( "You asked me to close, but not to I chose." );
}
}
}
Because making a Window close—and optionally exit the program—is a common operation,
I've encapsulated this into a small class called WindowCloser , which is in my public pack-
age com.darwinsys.util . Most AWT and Swing books have similar classes. Example 14-5
contains my WindowCloser class. Note that the class is marked deprecated; this serves as a
Search WWH ::




Custom Search