Basics of Event Handling

   

Core Java™ 2: Volume I - Fundamentals
By Cay S. Horstmann, Gary Cornell
Table of Contents
Chapter 8.  Event Handling


Any operating environment that supports GUIs constantly monitors events such as keystrokes or mouse clicks. The operating environment reports these events to the programs that are running. Each program then decides what, if anything, to do in response to these events. In languages like Visual Basic, the correspondence between events and code is obvious. One writes code for each specific event of interest and places the code in what is usually called an event procedure. For example, a Visual Basic button named HelpButton would have a HelpButton_Click event procedure associated with it, and VB would activate the code in this procedure in response to that button being clicked. Each Visual Basic user interface component responds to a fixed set of events, and it is impossible to change the events to which a Visual Basic component responds.

On the other hand, if you use a language like raw C to do event-driven programming, you need to write the code that checks the event queue constantly for what the operating environment is reporting. (You usually do this by encasing your code in a giant loop with a massive switch statement!) This technique is obviously rather ugly, and, in any case, it is much more difficult to code. The advantage is that the events you can respond to are not as limited as in languages, like Visual Basic, that go to great lengths to hide the event queue from the programmer.

Java takes an approach somewhat between the Visual Basic approach and the raw C approach in terms of power and, therefore, in resulting complexity. Within the limits of the events that the AWT knows about, you completely control how events are transmitted from the event sources (such as buttons or scrollbars) to event listeners. You can designate any object to be an event listener in practice, you pick an object that can conveniently carry out the desired response to the event. This event delegation model gives you much more flexibility than is possible with Visual Basic, where the listener is predetermined, but it requires more code and is more difficult to untangle (at least until you get used to it).

Event sources have methods that allow you to register event listeners with them. When an event happens to the source, the source sends a notification of that event to all the listener objects that were registered for that event.

As one would expect in an object-oriented language like Java, the information about the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class java.util.EventObject. Of course, there are subclasses for each event type, such as ActionEvent and WindowEvent.

Different event sources can produce different kinds of events. For example, a button can send ActionEvent objects, whereas a window can send WindowEvent objects.

To sum up, here's an overview of how event handling in the AWT works.

  • A listener object is an instance of a class that implements a special interface called (naturally enough) a listener interface.

  • An event source is an object that can register listener objects and send them event objects.

  • The event source sends out event objects to all registered listeners when that event occurs.

  • The listener objects will then use the information in the event object to determine their reaction to the event.

You register the listener object with the source object by using lines of code that follow the model:

 eventSourceObject.addEventListener(eventListenerObject); 

For example,

 ActionListener listener = . . .; JButton button = new JButton("Ok"); button.addActionListener(listener); 

Now the listener object is notified whenever an "action event" occurs in the button. For buttons, as you might expect, an action event is a button click.

Code like the above requires that the class to which the listener object belongs implements the appropriate interface (which in this case is the ActionListener interface). As with all interfaces in Java, implementing an interface means supplying methods with the right signatures. To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.

 class MyListener    implements ActionListener {    . . .    public void actionPerformed(ActionEvent event)    {       // reaction to button click goes here       . . .    } } 

Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls listener.actionPerformed(event) passing that event object. It is possible for multiple objects to be added as listeners to an event source such as a button. In that case, the button calls the actionPerformed methods of all listeners whenever the user clicks the button.

Figure 8-1 shows the interaction between the event source, event listener, and event object.

Figure 8-1. Event notification

graphics/08fig01.gif

graphics/notes_icon.gif

In this chapter, we put particular emphasis on event handling for user interface events such as button clicks and mouse moves. However, the basic event handling architecture is not specific to user interfaces. For example, in the JavaBeans chapter of Volume 2 you will see how to a component can fire events when its properties change.

Example: Handling a button click

As a way of getting comfortable with the event delegation model, let's work through all details needed for the simple example of responding to a button click. For this example, we will want:

  • A panel populated with three buttons;

  • Three listener objects that are added as action listeners to the buttons.

With this scenario, each time a user clicks on any of the buttons on the panel, the associated listener object then receives an ActionEvent that indicates a button click. In our sample program, the listener object will then change the background color of the panel.

Before we can show you the program that listens to button clicks, we first need to explain how to create buttons and how to add them to a panel. (For more on GUI elements, please see Chapter 9.)

You create a button by specifying a label string, an icon, or both in the button constructor. Here are two examples:

 JButton yellowButton = new JButton("Yellow"); JButton blueButton = new JButton(new ImageIcon("blue-ball.gif")); 

Adding buttons to a panel occurs through a call to a method named (quite mnemonically) add. The add method takes as a parameter the specific component to be added to the container. For example,

 class ButtonPanel extends JPanel {    public ButtonPanel()    {       JButton yellowButton = new JButton("Yellow");       JButton blueButton = new JButton("Blue");       JButton redButton = new JButton("Red");       add(yellowButton);       add(blueButton);       add(redButton);    } } 

Figure 8-2 shows the result.

Figure 8-2. A panel filled with buttons

graphics/08fig02.gif

Now that you know how to add buttons to a panel, you'll need to add code that lets the panel listen to these buttons. This requires classes that implement the ActionListener interface, which, as we just mentioned, has one method: actionPerformed, whose signature looks like this:

 public void actionPerformed(ActionEvent event) 

graphics/notes_icon.gif

The ActionListener interface we used in the button example is not restricted to button clicks. It is used in many separate situations such as:

  • When an item is selected from a list box with a double click;

  • When a menu item is selected;

  • When the ENTER key is clicked in a text field;

  • When a certain amount of time has elapsed for a Timer component.

You will see more details in this chapter and the next.

The way to use the ActionListener interface is the same in all situations: the actionPerformed method (which is the only method in ActionListener) takes an object of type ActionEvent as a parameter. This event object gives you information about the event that happened.

When a button is clicked, then we want to set the background color of the panel to a particular color. We store the desired color in our listener class.

 class ColorAction implements ActionListener {    public ColorAction(Color c)    {       backgroundColor = c;    }    public void actionPerformed(ActionEvent event)    {       // set panel background color       . . .    }    private Color backgroundColor; } 

We then construct one object for each color and set the objects as the button listeners.

 ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); 

For example, if a user clicks on the button marked "Yellow," then the actionPerformed method of the yellowAction object is called. Its backgroundColor instance field is set to Color.YELLOW, and it can now proceed to set the panel's background color.

There is just one remaining issue. The ColorAction object doesn't have access to the panel variable. You can solve this problem in two ways. You can store the panel in the ColorAction object and set it in the ColorAction constructor. Or, more conveniently, you can make ColorAction into an inner class of the ButtonPanel class. Then its methods can access the outer panel automatically. (For more information on inner classes, see Chapter 6.)

We will follow the latter approach. Here is how you place the ColorAction class inside the ButtonPanel class.

 class ButtonPanel extends JPanel {    . . .    private class ColorAction implements ActionListener    {       . . .       public void actionPerformed(ActionEvent event)       {          setBackground(backgroundColor);          // i.e. outer.setBackground(...)       }       private Color backgroundColor;    } } 

Look closely at the actionPerformed method. The ColorAction class doesn't have a setBackground method. But the outer ButtonPanel class does. The methods are invoked on the ButtonPanel object that constructed the inner class objects. (Note again that outer is not a keyword in the Java programming language. We just use it as an intuitive symbol for the invisible outer class reference in the inner class object.)

This situation is very common. Event listener objects usually need to carry out some action that affects other objects. You can often strategically place the listener class inside the class whose state the listener should modify.

Example 8-1 contains the complete program. Whenever you click one of the buttons, the appropriate action listener changes the background color of the panel.

Example 8-1 ButtonTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4.  5. public class ButtonTest  6. {  7.    public static void main(String[] args)  8.    {  9.       ButtonFrame frame = new ButtonFrame(); 10.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11.       frame.show(); 12.    } 13. } 14. 15. /** 16.    A frame with a button panel 17. */ 18. class ButtonFrame extends JFrame 19. { 20.    public ButtonFrame() 21.    { 22.       setTitle("ButtonTest"); 23.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 24. 25.       // add panel to frame 26. 27.       ButtonPanel panel = new ButtonPanel(); 28.       Container contentPane = getContentPane(); 29.       contentPane.add(panel); 30.    } 31. 32.    public static final int DEFAULT_WIDTH = 300; 33.    public static final int DEFAULT_HEIGHT = 200; 34. } 35. 36. /** 37.    A panel with three buttons. 38. */ 39. class ButtonPanel extends JPanel 40. { 41.    public ButtonPanel() 42.    { 43.       // create buttons 44. 45.       JButton yellowButton = new JButton("Yellow"); 46.       JButton blueButton = new JButton("Blue"); 47.       JButton redButton = new JButton("Red"); 48. 49.       // add buttons to panel 50. 51.       add(yellowButton); 52.       add(blueButton); 53.       add(redButton); 54. 55.       // create button actions 56. 57.       ColorAction yellowAction = new ColorAction(Color.YELLOW); 58.       ColorAction blueAction = new ColorAction(Color.BLUE); 59.       ColorAction redAction = new ColorAction(Color.RED); 60. 61.       // associate actions with buttons 62. 63.       yellowButton.addActionListener(yellowAction); 64.       blueButton.addActionListener(blueAction); 65.       redButton.addActionListener(redAction); 66.    } 67. 68.    /** 69.       An action listener that sets the panel's background color. 70.    */ 71.    private class ColorAction implements ActionListener 72.    { 73.       public ColorAction(Color c) 74.       { 75.           backgroundColor = c; 76.       } 77. 78.       public void actionPerformed(ActionEvent event) 79.       { 80.           setBackground(backgroundColor); 81.       } 82. 83.       private Color backgroundColor; 84.    } 85. } 

graphics/notes_icon.gif

If you have programmed graphical user interfaces in Java 1.0, then you may well be horribly confused after reading this section. In Java 1.0, life was simple: you didn't need to worry about listeners. Instead, you added code in methods like action and handleEvent to the classes that contained the user interface elements. For example, testing a button click would look like this:

 class ButtonPanel {    . . .    public boolean action(Event event, Object arg)    {       if (arg.equals("Yellow")) setBackground(Color.YELLOW);       else if (arg.equals("Blue")) setBackground(Color.BLUE);       else if (arg.equals("Red")) setBackground(Color.RED);       return true;    } } 

There are two important differences between the new event model and the older one:

  1. In Java 1.0, a button click is always received by the object that contains the button (that is, the panel). Now, information about the button click is sent only to objects that were added as an actionListener for the button.

  2. In Java 1.0, all events are caught in the action and handleEvent methods. Now, there are many separate methods (such as actionPerformed and windowClosing) that can react to events.

For simple programs, the old event model is easier to program (although whether it is conceptually as simple is another question). But for complex programs, the old event model has severe limitations. The new model, while initially more involved, is far more flexible and is potentially faster since events are sent only to the listeners that are actually interested in them.

java.swing.JButton 1.2

graphics/api_icon.gif
  • JButton(String label)

    constructs a button. The label string can be plain text, or, starting with J2SE 1.3, HTML; for example, "<HTML><B>Ok</B></HTML>".

    Parameters:

    label

    The text you want on the face of the button

  • JButton(Icon icon)

    constructs a button.

    Parameters:

    icon

    The icon you want on the face of the button

  • JButton(String label, Icon icon)

    constructs a button.

    Parameters:

    label

    The text you want on the face of the button

     

    icon

    The icon you want on the face of the button

java.awt.Container 1.0

graphics/api_icon.gif
  • Component add(Component c)

    adds a component to this container and adds c.

java.swing.ImageIcon 1.2

graphics/api_icon.gif
  • ImageIcon(String filename)

    constructs an icon whose image is stored in a file. The image is automatically loaded with a media tracker (see Chapter 7).

Becoming Comfortable with Inner Classes

Some people dislike inner classes because they feel that a proliferation of classes and objects makes their programs slower. Let's have a look at that claim. First of all, you don't need a new class for every user interface component. In our example, all three buttons share the same listener class. Of course, each of them has a separate listener object. But these objects aren't large. They each contain a color value and a reference to the panel. And the traditional solution, with if . . . else statements, also references the same color objects that the action listeners store, just as local variables and not as instance variables.

We believe the time has come to get used to inner classes. We recommend that you use dedicated inner classes for event handlers rather than turning existing classes into listeners. We think that even anonymous inner classes have their place.

Here is a good example how anonymous inner classes can actually simplify your code. If you look at the code of Example 8-1, you will note that each button requires the same treatment:

  1. Construct the button with a label string.

  2. Add the button to the panel.

  3. Construct an action listener with the appropriate color.

  4. Add that action listener.

Let's implement a helper method to simplify these tasks:

 void makeButton(String name, Color backgroundColor) {    JButton button = new JButton(name);    add(button);    ColorAction action = new ColorAction(backgroundColor);    button.addActionListener(action); } 

Then the ButtonPanel constructor simply becomes

 public ButtonPanel() {    makeButton("yellow", Color.YELLOW);    makeButton("blue", Color.BLUE);    makeButton("red", Color.RED); } 

Now you can make a further simplification. Note that the ColorAction class is only needed once: in the makeButton method. Therefore, you can make it into an anonymous class:

 void makeButton(String name, final Color backgroundColor) {    JButton button = new JButton(name);    add(button);    button.addActionListener(new       ActionListener()       {          public void actionPerformed(ActionEvent event)          {             setBackground(backgroundColor);          }       }); } 

The action listener code has become quite a bit simpler. The actionPerformed method simply refers to the parameter variable backgroundColor. (As with all local variables that are accessed in the inner class, the parameter needs to be declared as final.)

No explicit constructor is needed. As you saw in Chapter 6, the inner class mechanism automatically generates a constructor that stores all local final variables that are used in one of the methods of the inner class.

graphics/exclamatory_icon.gif

Anonymous inner classes can look confusing. But you can get used to deciphering them if you train your eyes to glaze over the routine code, like this:

 button.addActionListener(new ActionListener() {    public void actionPerformed(ActionEvent event)    {       setBackground(backgroundColor);    } }); 

That is, the button action is to set the background color. As long as the event handler consists of just a few statements, we think this can be quite readable, particularly if you don't worry about the inner class mechanics.

graphics/exclamatory_icon.gif

SDK 1.4 introduces a mechanism that lets you specify simple event listeners without programming inner classes. For example, suppose you have a button labeled Load whose event handler contains a single method call:

 frame.loadData(); 

Of course, you can use an anonymous inner class:

 loadButton.addActionListener(new    ActionListener()    {       public void actionPerformed(ActionEvent event)       {          frame.loadData();       }    }; 

But the EventHandler class can create such a listener automatically, with the call

 EventHandler.create(ActionListener.class, frame, "loadData") 

Of course, you still need to install the handler:

 loadButton.addActionListener((ActionListener)    EventHandler.create(ActionListener.class, frame,    "loadData")); 

The cast is necessary because the create method returns an Object.

This is certainly a convenience if an event listener happens to call a method without parameters.

If the event listener calls a method with a single parameter that is derived from the event handler, then you can use another form of the create method. For example, the call

 EventHandler.create(ActionListener.class, frame,    "loadData", "source.text") 

is equivalent to

 new ActionListener() {    public void actionPerformed(ActionEvent event)    {       frame.loadData(          ((JTextField)event.getSource()).getText());    } } 

Note that the event handler turns the names of the properties source and text into method calls getSource and getText, using the Java Beans convention. (For more information on properties and Java Beans, please turn to volume 2.)

However, in practice, this situation is not all that common, and there is no mechanism for supplying parameters that aren't derived from the event object.

Turning Components into Event Listeners

You are completely free to designate any object of a class that implements the ActionListener interface as a button listener. We prefer to use objects of a new class that was expressly created for carrying out the desired button actions. However, some programmers are not comfortable with inner classes and choose a different strategy. They locate the component that changes as a result of the event, make that component implement the ActionListener interface, and add an actionPerformed method. In our example, you can turn the ButtonPanel into an action listener:

 class ButtonPanel extends JPanel    implements ActionListener {    . . .    public void actionPerformed(ActionEvent event)    {       // set background color       . . .    } } 

Then the panel sets itself as the listener to all three buttons:

 yellowButton.addActionListener(this); blueButton.addActionListener(this); redButton.addActionListener(this); 

Note that now the three buttons no longer have individual listeners. They share a single listener object, namely the button panel. Therefore, the actionPerformed method must figure out which button was clicked.

The getSource method of the EventObject class, the superclass of all other event classes, will tell you the source of every event. The event source is the object that generated the event and notified the listener:

 Object source = event.getSource(); 

The actionPerformed method can then check which of the buttons was the source:

 if (source == yellowButton) . . . else if (source == blueButton) . . . else if (source == redButton ) . . . 

Of course, this approach requires that you keep references to the buttons as instance fields in the surrounding panel.

As you can see, turning the button panel into the action listener isn't really any simpler than defining an inner class. It also becomes really messy when the panel contains multiple user interface elements.

graphics/caution_icon.gif

Some programmers use a different way to find out the event source in a listener object that is shared among multiple sources. The ActionEvent class has a getActionCommand method that returns the command string associated with this action. For buttons, it turns out that the command string defaults to being the button label. If you take this approach, an actionPerformed method contains code like this:

 String command = event.getActionCommand(); if (command.equals("Yellow")) . . .; else if (command.equals("Blue")) . . .; else if (command.equals("Red")) . . .; 

We suggest that you do not follow this approach. Relying on the button strings is dangerous. It is an easy mistake to label a button "Gray" and then spell the string slightly differently in the test:

 if (command.equals("Grey")) . . . 

And button strings give you grief when the time comes to internationalize your application. To make the German version with button labels "Gelb," "Blau," and "Rot," you have to change both the button labels and the strings in the actionPerformed method.

java.util.EventObject 1.1

graphics/api_icon.gif
  • Object getSource()

    returns a reference to the object where the event initially occurred.

java.awt.event.ActionEvent 1.1

graphics/api_icon.gif
  • String getActionCommand()

    returns the command string associated with this action event. If the action event originated from a button, the command string equals the button label, unless it has been changed with the setActionCommand method.

java.beans.EventHandler 1.4

graphics/api_icon.gif
  • static Object create(Class listenerInterface, Object target, String action)

  • static Object create(Class listenerInterface, Object target, String action, String eventProperty)

  • static Object create(Class listenerInterface, Object target, String action, String eventProperty, String listenerMethod)

    These methods construct an object of a proxy class that implements the given interface. Either the named method, or all methods of the interface, carry out the given action on the target object.

    The action can be a method name or a property of the target. If it is a property, its setter method is executed. For example, an action "text" is turned into a call of the setText method.

    The event property consists of one or more dot-separated property names. The first property is read from the parameter of the listener method. The second property is read from the resulting object, and so on. The final result becomes the parameter of the action. For example, the property "source.text" is turned into calls to the getSource and getText methods.

Example: Changing the Look and Feel

By default, Swing programs use the Metal look and feel. There are two ways to change to a different look and feel. You can supply a file swing.properties in the jdk/jre/lib directories that sets the property swing.defaultlaf to the class name of the look and feel that you want. For example,

 swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel 

Note that the Metal look and feel is located in the javax.swing package. The other look and feel packages are located in the com.sun.java package and need not be present in every Java implementation. Currently, for copyright reasons, the Windows and Mac look and feel packages are only shipped with the Windows and Mac versions of the Java Runtime Environment.

graphics/exclamatory_icon.gif

Here is a useful tip for testing. Since lines starting with a # character are ignored in property files, you can supply several look and feel selections in the swing.properties file and move around the # to select one of them:

[View full width]

#swing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel #swing.defaultlaf=com.sun.java.swing.plaf.windows. graphics/ccc.gifWindowsLookAndFeel

You must restart your program to switch the look and feel in this way. A Swing program reads the swing.properties file only once, at startup.

To change the look and feel dynamically, call the static UIManager.setLook-AndFeel method and give it the name of the look and feel that you want. Then call the static method SwingUtilities.updateComponentTreeUI to refresh the entire set of components. You need to supply one component to that method; it will find all others. The UIManager.setLookAndFeel method may throw a number of exceptions when it can't find the look and feel that you request, or when there is an error loading it. As always, we ask you to gloss over the exception handling code and wait until Chapter 11 for a full explanation.

Here is an example showing how you can switch to the Motif look and feel in your program:

 String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; try {    UIManager.setLookAndFeel(plaf);    SwingUtilities.updateComponentTreeUI(panel); } catch(Exception e) { e.printStackTrace(); } 

Example 8-2 is a complete program that demonstrates how to switch the look and feel (see Figure 8-3). The program is very similar to Example 8-1. Following the advice of the preceding section, we use a helper method makeButton and an anonymous inner class to specify the button action, namely to switch the look and feel.

Figure 8-3. Switching the Look and Feel

graphics/08fig03.gif

There is one fine point to this program. The actionPerformed method of the inner action listener class needs to pass the this reference of the outer PlafPanel class to the updateCompnentTreeUI method. Recall from Chapter 6 that the outer object's this pointer must be prefixed by the outer class name:

 SwingUtilities.updateComponentTreeUI(PlafPanel.this); 

Note that the "Windows" button will only work on Windows since Sun does not supply the Windows look and feel on other platforms.

Example 8-2 PlafTest.java
  1. import java.awt.*;  2. import java.awt.event.*;  3. import javax.swing.*;  4.  5. public class PlafTest  6. {  7.    public static void main(String[] args)  8.    {  9.       PlafFrame frame = new PlafFrame(); 10.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 11.       frame.show(); 12.    } 13. } 14. 15. /** 16.     A frame with a button panel for changing look and feel 17. */ 18. class PlafFrame extends JFrame 19. { 20.    public PlafFrame() 21.    { 22.       setTitle("PlafTest"); 23.       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 24. 25.       // add panel to frame 26. 27.       PlafPanel panel = new PlafPanel(); 28.       Container contentPane = getContentPane(); 29.       contentPane.add(panel); 30.    } 31. 32.    public static final int DEFAULT_WIDTH = 300; 33.    public static final int DEFAULT_HEIGHT = 200; 34. } 35. 36. /** 37.     A panel with buttons to change the pluggable look and feel 38. */ 39. class PlafPanel extends JPanel 40. { 41.    public PlafPanel() 42.    { 43.       makeButton("Metal", 44.          "javax.swing.plaf.metal.MetalLookAndFeel"); 45.       makeButton("Motif", 46.          "com.sun.java.swing.plaf.motif.MotifLookAndFeel"); 47.       makeButton("Windows", 48.          "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 49.    } 50. 51.    /** 52.       Makes a button to change the pluggable look and feel. 53.       @param name the button name 54.       @param plafName the name of the look and feel class 55.     */ 56.    void makeButton(String name, final String plafName) 57.    { 58.       // add button to panel 59. 60.       JButton button = new JButton(name); 61.       add(button); 62. 63.       // set button action 64. 65.       button.addActionListener(new 66.          ActionListener() 67.          { 68.             public void actionPerformed(ActionEvent event) 69.             { 70.                // button action: switch to the new look and feel 71.                try 72.                { 73.                   UIManager.setLookAndFeel(plafName); 74.                   SwingUtilities.updateComponentTreeUI 75.                      (PlafPanel.this); 76.                } 77.                catch(Exception e) { e.printStackTrace(); } 78.             } 79.          }); 80.    } 81. } 

Example: Capturing Window Events

Not all events are as simple to handle as button clicks. Here is an example of a more complex case that we already briefly noted in Chapter 7. Prior to the appearance of the EXIT_ON_CLOSE option in the Java SDK 1.3, programmers had to manually exit the program when the main frame was closed. In a non-toy program, you will want to do that as well, because you only want to close the program after you checked that the user won't lose work. For example, when the user closes the frame, you may want to put up a dialog to warn the user if unsaved work is about to be lost, and only exit the program when the user agrees.

When the program user tries to close a frame window, the JFrame object is the source of a WindowEvent. If you want to catch that event, you must have an appropriate listener object and add it to the list of window listeners.

 WindowListener listener = . . .; frame.addWindowListener(listener); 

The window listener must be an object of a class that implements the WindowListener interface. There are actually seven methods in the WindowListener interface. The frame calls them as the responses to seven distinct events that could happen to a window. The names are self-explanatory, except that "iconified" is usually called "minimized" under Windows. Here is the complete WindowListener interface:

 public interface WindowListener {    void windowOpened(WindowEvent e);    void windowClosing(WindowEvent e);    void windowClosed(WindowEvent e);    void windowIconified(WindowEvent e);    void windowDeiconified(WindowEvent e);    void windowActivated(WindowEvent e);    void windowDeactivated(WindowEvent e); } 

graphics/notes_icon.gif

If you want to find out whether a window has been maximized, you need to install a WindowStateListener. See the API notes below for details.

As is always the case in Java, any class that implements an interface must implement all its methods; in this case, this means implementing seven methods. Recall that we are only interested in one of these seven methods, namely the windowClosing method.

Of course, we can define a class that implements the interface, add a call to System.exit(0) in the windowClosing method, and write do-nothing functions for the other six methods:

 class Terminator implements WindowListener {    public void windowClosing(WindowEvent e)    {       System.exit(0);    }    public void windowOpened(WindowEvent e) {}    public void windowClosed(WindowEvent e) {}    public void windowIconified(WindowEvent e) {}    public void windowDeiconified(WindowEvent e) {}    public void windowActivated(WindowEvent e) {}    public void windowDeactivated(WindowEvent e) {} } 
Adapter Classes

Typing code for six methods that don't do anything is the kind of tedious busywork that nobody likes. To simplify this task, each of the AWT listener interfaces that has more than one method comes with a companion adapter class that implements all the methods in the interface but does nothing with them. For example, the WindowAdapter class has seven do-nothing methods. This means the adapter class automatically satisfies the technical requirements that Java imposes for implementing the associated listener interface. You can extend the adapter class to specify the desired reactions to some, but not all, of the event types in the interface. (An interface such as ActionListener that has only a single method does not need an adapter class.)

Let us make use of the window adapter. We can extend the WindowAdapter class, inherit six of the do-nothing methods, and override the windowClosing method:

 class Terminator extends WindowAdapter {    public void windowClosing(WindowEvent e)    {       System.exit(0);    } } 

graphics/notes_icon.gif

You may recall that some programmers like to turn components into event listeners. But that trick won't work here. You cannot make MyFrame into a subclass of WindowAdapter since MyFrame already extends JFrame. Therefore, you cannot simply set the window listener to this, and you must come up with a new class.

Now you can register an object of type Terminator as the event listener:

 WindowListener listener = new Terminator(); frame.addWindowListener(listener); 

Now, whenever the frame generates a window event, it passes it to the listener object by calling one of its seven methods (see Figure 8-4). Six of those methods do nothing; the windowClosing method calls System.exit(0), terminating the application.

Figure 8-4. A window listener

graphics/08fig04.gif

Creating a listener class that extends the WindowAdapter is an improvement, but we can go even further. There is no need to give a name to the listener object. Simply write

 frame.addWindowListener(new Terminator()); 

But why stop there? We can make the listener class into an anonymous inner class of the frame.

 frame.addWindowListener(new    WindowAdapter()    {       public void windowClosing(WindowEvent e)       {          System.exit(0);       }    } ); 

This code does the following:

  • Defines a class without a name that extends the WindowAdapter class.

  • Adds a windowClosing method to that anonymous class. (As before, this method exits the program.)

  • Inherits the remaining six do-nothing methods from WindowAdapter.

  • Creates an object of this class. That object does not have a name, either.

  • Passes that object to the addWindowListener method.

As we already mentioned, the syntax for using anonymous inner classes for event listeners takes some getting used to. The payoff is that the resulting code is as short as possible.

You will see this code in many example programs. Before the EXIT_ON_CLOSE option came along, all graphical applications needed to supply it.

java.awt.event.WindowListener 1.1

graphics/api_icon.gif
  • void windowOpened(WindowEvent e)

    This method is called after the window has been opened.

  • void windowClosing(WindowEvent e)

    This method is called when the user has issued a window manager command to close the window. Note that the window will only close if its hide or dispose method is called.

  • void windowClosed(WindowEvent e)

    This method is called after the window has closed.

  • void windowIconified(WindowEvent e)

    This method is called after the window has been iconified.

  • void windowDeiconified(WindowEvent e)

    This method is called after the window has been deiconified.

  • void windowActivated(WindowEvent e)

    This method is called after the window has become active. Only a frame or dialog can be active. Typically, the window manager decorates the active window, for example by highlighting the title bar.

  • void windowDeactivated(WindowEvent e)

    This method is called after the window has become deactivated.

java.awt.event.WindowStateListener 1.4

graphics/api_icon.gif
  • void windowStateChanged(WindowEvent event)

    This method is called after the window has been maximized, iconified, or restored to its normal size.

java.awt.event.WindowEvent 1.1

graphics/api_icon.gif
  • int getNewState() 1.4

  • int getOldState() 1.4

    These methods return the new and old state of a window in a window state change event. The returned integer is one of the following values:

     Frame.NORMAL Frame.ICONIFIED Frame.MAXIMIZED_HORIZ Frame.MAXIMIZED_VERT Frame.MAXIMIZED_BOTH 


       
    Top
     



    Core Java 2(c) Volume I - Fundamentals
    Building on Your AIX Investment: Moving Forward with IBM eServer pSeries in an On Demand World (MaxFacts Guidebook series)
    ISBN: 193164408X
    EAN: 2147483647
    Year: 2003
    Pages: 110
    Authors: Jim Hoskins

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net