Main Page

Previous Next

Event Classes

There are many different kinds of events to which your program may need to respond – from menus, buttons, from the mouse, from the keyboard, and a number of others. In order to have a structured approach to handling events, these are broken down into subsets. At the topmost level, there are two broad categories of events in Java:

  • Low-level Events – these are events that arise from the keyboard or from the mouse, or events associated with operations on a window such as reducing it to an icon or closing it. The meaning of a low-level event is something like 'the mouse was moved', 'this window has been closed' or 'this key was pressed.

  • Semantic Events – these are specific component-related events such as pressing a button by clicking it to cause some program action, or adjusting a scrollbar. They originate, and you interpret them, in the context of the GUI you have created for your program. The meaning of a semantic event is typically along the lines of: 'the OK button was pressed', or 'the Save menu item was selected'. Each kind of component, a button, or a menu item for example, can generate a particular kind of semantic event.

These two categories can seem to be a bit confusing as they overlap in a way. If you click a button, you create a semantic event as well as a low level event. The click produces a low-level event object in the form of 'the mouse was clicked' as well as a semantic event 'the button was pushed'. In fact it produces more than one mouse event, as we shall see. Whether your program handles the low-level events or the semantic event, or possibly both kinds of event, depends on what you want to do.

Most of the events relating to the GUI for a program are represented by classes defined in the package java.awt.event. This package also defines the listener interfaces for the various kinds of events that it defines. The package javax.swing.event defines classes for events that are specific to Swing components.

Low-level Event Classes

There are four kinds of low-level events that you can elect to handle in your programs. They are represented by the following classes in the java.awt.event package:

Event

Description

FocusEvent

Objects of this class represent events that originate when a component gains or loses the keyboard focus. Only the component that has the focus can receive input from the keyboard, so it will usually be highlighted or have the cursor displayed.

MouseEvent

Objects of this class represent events that result from user actions with the mouse such as moving the mouse or pressing a mouse button.

KeyEvent

Objects of this class represent events that arise from pressing keys on the keyboard.

WindowEvent

Objects of this class represent events that relate to a window, such as activating or deactivating a window, reducing a window to its icon, or closing a window. These events relate to objects of the Window class or any subclass of Window.

The MouseEvent class has two subclasses that identify more specialized mouse events. One is the MenuDragMouseEvent class that defines event objects signaling when the mouse has been dragged over a menu item. The other is the MouseWheelEvent class that defines event objects indicating when the mouse wheel is rotated.

Important 

Just so that you know, this isn't an exhaustive list of all of the low-level event classes. It's a list of the ones you need to know about. For example, there's the PaintEvent class that is concerned with the internals of how components get painted on the screen. There's also another low-level event class, ContainerEvent, which defines events relating to a container such as adding or removing components. You can ignore this class as these events are handled automatically.

Each of these classes defines methods that enable you to analyze the event. For a MouseEvent object, for example, you can get the coordinates of the cursor when the event occurred. These low-level event classes also inherit methods from their superclasses, and are related in the manner shown in the diagram:

The class AWTEvent is itself a subclass of java.util.EventObject. The EventObject class implements the Serializable interface, so all objects of the event classes in the diagram are serializable. It also defines a method, getSource(), which returns the object that is the source of an event as type Object. All the event classes shown inherit this method.

The class AWTEvent defines constants, which are public final values identifying the various kinds of events. These constants are named for the sake of consistency as the event name in capital letters, followed by _MASK. The constants identifying the low-level events that you are most likely to be interested in are:

MOUSE_EVENT_MASK

MOUSE_MOTION_EVENT_MASK

MOUSE_WHEEL_EVENT_MASK

KEY_EVENT_MASK

ADJUSTMENT_EVENT_MASK

TEXT_EVENT_MASK

WINDOW_EVENT_MASK

WINDOW_FOCUS_EVENT_MASK

WINDOW_STATUS_EVENT_MASK

ITEM_EVENT_MASK

FOCUS_EVENT_MASK

 

Each of these constants is a value of type long with a single bit being set to 1 and all the remaining set to 0. Because they are defined this way you can combine them using a bitwise OR operator and you can separate a particular constant out from a combination by using a bitwise AND.

Important 

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
    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,
JavaScript Editor
 Java Tutorials Free JavaScript Editor