Java Reference
In-Depth Information
FocusAdapter
WindowAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
MouseInputAdapter
The
WindowAdapter
class implements all of the methods defined in the
WindowListener
,
WindowFocusListener
, and
WindowStateListener
interfaces. The other five each implement the
methods in the corresponding listener interface.
To handle the window closing event for the Sketcher application, we could derive our own class from
the
WindowAdapter
class and just implement the
windowClosing()
method. If we also make it an
inner class for the class
Sketcher
, it will automatically have access to the members of the
Sketcher
object, regardless of their access specifiers.
Try It Out - Implementing an Adapter Class
The version of the
Sketcher
class to implement this will be as follows, with changes to the previous
version highlighted:
// Sketching application
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the application object
theApp.init(); // ...and initialize it
}
// Initialization of the application
public void init() {
window = new SketchFrame("Sketcher");
Toolkit theKit = window.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to 2/3 screen size
window.setBounds(wndSize.width/6, wndSize.height/6, // Position
2*wndSize.width/3, 2*wndSize.height/3); // Size
window.addWindowListener(new WindowHandler()); // Add window listener
window.setVisible(true); // Display the window
}
// Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
public void windowClosing(WindowEvent e) {
window.dispose(); // Release the window resources
System.exit(0); // End the application
}