Java Reference
In-Depth Information
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
enableEvents(AWTEvent.WINDOW _ EVENT _ MASK); // Enable window events
}
// Handle window events
protected 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;
// Element menu items
private JRadioButtonMenuItem lineItem, rectangleItem, circleItem, // Types
curveItem, textItem;
private JCheckBoxMenuItem redItem, yellowItem, // Colors
greenItem, blueItem ;
}
We add the call to enableEvents() as the last in the constructor. Note that we have commented out
the statement that sets EXIT _ ON _ CLOSE as the close option for the window. You could delete the
statement if you want. When you compile SketchFrame and run Sketcher , you'll be able to close
the window as before, and the program will shut down gracefully. However, this time it's our method
that's doing it.
How It Works
The import statement makes the java.awt.event package and its various event classes available to
the class file. We call enableEvents() in the constructor with WINDOW _ EVENT _ MASK as the
argument to enable window events. This enables all the window events represented 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 class. The event IDs for
the WindowEvent class are:
Event ID
Description
WINDOW _ OPENED
The event that occurs the first time a window is made visible.
WINDOW _ CLOSING
The event that occurs as a result of the close icon being
selected or Close being selected from the window's system
menu.
Search WWH ::




Custom Search