Java Reference
In-Depth Information
// Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
public void windowClosing(WindowEvent e) {
window.checkForSave();
}
}
Directory "Sketcher 5 checking for save on close and exit"
This ensures that a sketch is not lost when you click on the close icon for the application window.
How It Works
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. You saw in Chapter 18
that the
WindowListener
interface declares seven methods corresponding to various window events, but
you need just the
windowClosing()
method.
Clearly, using the
WindowAdapter
class as a base saves a lot of time and effort. Without it you would
have to define all seven of the methods declared in the interface in our class. Because the
WindowHandler
class is an inner class, its methods can access the fields of the
Sketcher
class, so the
windowClosing()
method can call the
checkForSave()
method for the
window
member of the
Sketcher
class object.
Now if you close the application window without having saved your sketch, you are prompted to save it.
Defining the
WindowHandler
inner class explicitly with just one method is not the only way to do this.
You could use an anonymous class, as the method is so simple. If you removed the
WindowHandler
in-
ner class from the Sketcher class, you could replace the statement that adds the window listener for the
window object with the following statement:
window.addWindowListener(new WindowAdapter() { // Add window
listener
public void windowClosing(WindowEvent
e) {
window.checkForSave();
}
} );
This defines an anonymous class derived from the
WindowHandler
class in the expression that is the ar-
gument to the
addWindowListener()
method. The syntax is exactly the same as if you were defining an
anonymous class that implements an interface. The class defines just one method, the
windowClosing()
method that you defined previously in the
WindowHandler
class.
This makes use of the code that you implemented for the save operation, packaged in the
check-
ForSave()
method. This does everything necessary to enable the sketch to be saved before the applica-
tion window is closed. Defining methods judiciously makes for economical coding.
This still leaves you with the File
⇒
Close and File
⇒
Exit items to tidy up. Closing a sketch is not
really any different from the File
⇒
New function, so you could implement it in exactly the same way.