Java Reference
In-Depth Information
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 identifier for the events you want enabled
as an argument. However, you do this only when you aren't using a listener. Registering a listener auto-
matically 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 listener objects is the preferred way of handling events because it is easier than enabling events dir-
ectly for an object, and the code is clearer. Nonetheless, you should take a look at how events are dealt with
after calling enableEvents() in case you come across it elsewhere. An example of where you might want
to call enableEvents() exists in the SketcherFrame class in the Sketcher program.
As you may recall from the previous chapter, you used the setDefaultCloseOperation() method to
determine what happens when you close the window by clicking the X icon. Although the EXIT_ON_CLOSE
argument value that you used disposed of the frame and closed the application, it didn't provide any oppor-
tunity to do any checking or cleanup before causing the program to exit. You can respond to the close icon
being clicked in the program yourself, rather than letting the JFrame facilities handle the associated event
within the window object itself. This eventually enables you to prompt the user to save any data that has
been created before shutting down the application. Let's give it a try.
TRY IT OUT: Closing a Window
You need to modify the SketcherFrame class definition from the Sketcher example in the previous
chapter as follows:
// Frame for the Sketcher application
import javax.swing.*;
import static java.awt.event.InputEvent.*; // For modifier
constants
import java.awt.event.WindowEvent;
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title) {
setTitle(title); // Set the
window title
// setDefaultCloseOperation(EXIT_ON_CLOSE);
// rest of code as before...
menuBar.add(fileMenu); // Add the file
menu
menuBar.add(elementMenu); // Add the
element menu
Search WWH ::




Custom Search