Java Reference
In-Depth Information
Preventing Data Loss on Close
At the moment we're still not calling checkForSave() when we close the application with the window
icon. This means we could lose hours of work in an instant. But it's very simple. We just need to get the event
handler for the window closing event to call the checkForSave() method for the window object.
Try It Out - Prompting for Save on Close
To implement this we can use the WindowListener for the application window that we have already
added in the Sketcher class. This listener receives notification of events associated with opening and
closing the window as well as minimizing and maximizing it. We just need to add some code to the
body of the windowClosing() method for the listener. We require one extra line in the Sketcher
class definition:
// Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
public void windowClosing(WindowEvent e) {
window.checkForSave();
}
}
The WindowHandler class is a subclass of the WindowAdapter class. In the subclass you just define the
methods you are interested in to override the empty versions in the adapter class. The WindowListener
interface declares the following seven methods corresponding to various window events:
Method
Description
windowActivated(WindowEvent e)
Called when the window receives the focus
and becomes the currently active window.
windowDeactivated(WindowEvent e)
Called when the window ceases to be the
currently active window.
windowIconified(WindowEvent e)
Called when the window is minimized.
windowDeiconified(WindowEvent e)
Called when the window returns to its
normal state from a minimized state.
windowOpened(WindowEvent e)
Called the first time a window is made
visible.
windowClosed(WindowEvent e)
Called when a window has been closed by
calling its dispose() method.
windowClosing(WindowEvent e)
Called when the user selects the close icon or
the Close item from the system menu for the
window.
Search WWH ::




Custom Search