Java Reference
In-Depth Information
@Override
public void windowClosing(WindowEvent e) {
window.dispose();
// Release the
window resources
System.exit(0);
// End the
application
}
}
private SketcherFrame window; // The
application window
private static Sketcher theApp; // The
application object
}
Directory "Sketcher 3 using an Adapter class"
This example displays the same application window as the previous example.
How It Works
As the
Sketcher
class is no longer the listener for
window
, it doesn't need to implement the
Win-
dowListener
interface. The
WindowHandler
class is the listener class for
window
events. Because the
WindowHandler
class is an inner class to the
Sketcher
class, it has access to all the members of the class,
so calling the
dispose()
method for the
window
object is still quite straightforward — you just access
the
window
field of the top-level class.
The
WindowAdapter
object that is the listener for the window object is created in the argument to the
addWindowListener()
method for
window
. You don't need an explicit variable to contain it because it
is stored in a data member of the
SketcherFrame
class that is inherited from the
Window
class.
WARNING
It is very important to use the
@Override
annotation when you are us-
ing adapter classes. An easy mistake to make when you
'
re using adapter classes is
to misspell the name of the method that you are using to implement the event — typ-
ically by using the wrong case for a letter. If you have not specified the
@Override
annotationforyourmethod,youwon
'
tgetanyindicationofthis.Youaren
'
toverrid-
ing the adapter class method at all; you
'
re adding a new method. Your code should
compile perfectly well but your program does not handle any events. They are all
passed to the method in the adapter class with the name your method should have
had — which does nothing, of course.
You haven't finished with low-level events yet by any means, and you return to handling more low-level
events in the next chapter when you begin to add drawing code to the Sketcher program. In the mean-
time, let's start looking at how you can manage semantic events.
Semantic Events