Java Reference
In-Depth Information
The list of event masks above is not exhaustive. There are masks for component events
represented by objects of the class ComponentEvent , and for container events.
These events occur when a component is moved or resized, or a component is added to
a container, for example. There is also a mask for events associated with components
that receive text input. You won't normally need to get involved in these events so we
won't be discussing them further.
You use the identifiers for event masks to enable a particular group of events in a component object.
You call the enableEvents() method for the component, and pass the variable for the events you
want enabled as an argument. However, you only do this when you aren't using a listener. Registering a
listener automatically enables the events that the listener wants to hear, so you don't need to call the
enableEvents() method. The circumstance when you might do this is when you want an object to
handle some of its own events although you can achieve the same result using a listener.
Making a Window Handle its own Events
Using listeners is the preferred way of handling events since it is easier than enabling events directly for
an object, and the code is clearer. Nonetheless, we should take a look at how you deal with events after
calling enableEvents() . An example of where you might want to call enableEvents() exists in
our SketchFrame class in the Sketcher program.
As you may recall from the previous chapter, we used the setDefaultCloseOperation() method
to determine what happened when you close the window by clicking on the icon. Although the
EXIT _ ON _ CLOSE argument value that we used disposed of the frame and closed the application, it
didn't provide any opportunity to do any checking or clean-up before causing the program to exit. We
can respond to the close icon being clicked in the program ourselves, rather than letting the JFrame
facilities handle the associated event within the window object itself. This will eventually enable us to
prompt the user to save any data that has been created, and then shut down the application ourselves
when a close event occurs, so let's give it a try.
Try It Out - Closing a Window
We need to modify the SketchFrame class definition from the previous chapter as follows:
// Frame for the Sketcher application
import javax.swing.*;
import java.awt.Event;
import java.awt.AWTEvent;
import java.awt.event.WindowEvent;
public class SketchFrame extends JFrame {
// Constructor
public SketchFrame(String title) {
setTitle(title); // Set the window title
// setDefaultCloseOperation(EXIT _ ON _ CLOSE);
// rest of code as before
Search WWH ::




Custom Search