Java Reference
In-Depth Information
enableEvents(WINDOW_EVENT_MASK);
// Enable window
events
}
// Handle window events
protcted void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
dispose();
// Release resources
System.exit(0);
// Exit the program
}
super.processWindowEvent(e);
// Pass on the event
}
private JMenuBar menuBar = new JMenuBar(); // Window menu
bar
// File menu items
private JMenuItem newItem, openItem, closeItem,
saveItem, saveAsItem, printItem;
// Elements menu items
private JRadioButtonMenuItem lineItem, rectangleItem, circleItem,
// Types
curveItem, textItem;
private JCheckBoxMenuItem redItem, yellowItem,
// Colors
greenItem, blueItem ;
}
Directory "Sketcher 1 handling its own closing event"
You add the call to enableEvents() as the last in the constructor. Note that the statement that sets
EXIT_ON_CLOSE as the close option for the window is commented out. You could delete the statement if
you want. When you compile SketcherFrame and run Sketcher again, you are able to close the window
as before, and the program shuts down gracefully. However, this time it's your method that's doing it.
How It Works
The additional import statement makes the WindowEvent class name available to your source file
without the need to qualify it with the package name. You call enableEvents() in the constructor with
WINDOW_EVENT_MASK as the argument to enable window events. This enables all the window events rep-
resented by the WindowEvent class. An object of this class can represent one of a number of different
window events that are each identified by an event ID, which is a constant defined within the Win-
dowEvent class. The event IDs for the WindowEvent class are shown in Table 18-2 :
TABLE 18-2 : Event IDs for the WindowEvent Class
EVENT ID
DESCRIPTION
The event that occurs the first time a window is made visible.
WINDOW_OPENED
The event that occurs as a result of the close icon being selected or Close being se-
lected from the window's system menu.
WINDOW_CLOSING
The event that occurs when the window has been closed.
WINDOW_CLOSED
 
 
Search WWH ::




Custom Search