Java Reference
In-Depth Information
PITFALL: Forgetting to Invoke setDefaultCloseOperation
If you register a window listener to respond to window events from a JFrame, you
should also include an invocation of the method setDefaultCloseOperation,
typically in the JFrame constructor. This is because the default or other behavior set
by setDefaultCloseOperation takes place even if there is a window listener. If you
do not want any actions other than those provided by the window listener(s), you
should include the following in the JFrame constructor:
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
If you do not include any invocation of setDefaultCloseOperation, the default
action is the same as if you had included the invocation
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
which hides the JFrame when the close-window button is clicked. (The actions of any
registered window listener are also performed.)
The WindowAdapter Class
In Display 18.2, we gave empty bodies to most of the method headings in the
WindowListener interface. The abstract class WindowAdapter is a way to avoid all
those empty method bodies. The class WindowAdapter does little more than provide
trivial implementations of the method headings in the WindowListener interface. So, if
you make a window listener a derived class of the class WindowAdapter, then you have
only to define the method headings in the WindowListener interface that you need.
The other method headings inherit trivial implementations from WindowAdapter.
( WindowAdapter is unusual in that it is an abstract class with no abstract methods.)
For example, in Display 18.3 we have rewritten the inner class CheckOnExit from
Display 18.2, but this time we made it a derived class of the WindowAdapter class. This
definition of CheckOnExit is much shorter and cleaner than the one in Display 18.2,
but the two implementations of CheckOnExit are equivalent. Thus, you can replace the
definition of CheckOnExit in Display 18.2 with the shorter one in Display 18.3 . The file
WindowListenerDemo2 on the accompanying website contains a version of Display 18.2
with this shorter definition of CheckOnExit .
The class WindowAdapter is in the java.awt.event package and so requires an
import statement such as the following:
extra code
on website
import java.awt.event.WindowAdapter;
You cannot always define your window listeners as derived classes of Windowdapter.
For example, suppose you want a JFrame class to be its own window listener. To
accomplish this, the class must be a derived class of JFrame and so cannot be a derived
 
Search WWH ::




Custom Search