Friday 24 March 2017

The Delegation Event Model & Event Listener Interfaces - Java Tutorials

The Delegation Event Model

Before beginning our discussion of event handling, an important point must be made: The way in which events are handled by an applet changed significantly between the original version of Java (1.0) and modern versions of Java, beginning with version 1.1. The 1.0 method of event handling is still supported, but it is not recommended for new programs. Also, many of the methods that support the old 1.0 event model have been deprecated. The modern approach is the way that events should be handled by all new programs, including those written for Java 2, and thus is the method employed by programs in this book.

The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to “delegate” the processing of an event to a separate piece of code.

In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it was handled by a component. This required components to receive events that they did not process, and it wasted valuable time. The delegation event model eliminates this overhead.

Java also allows you to process events without using the delegation event model. This can be done by extending an AWT component. However, the delegation event model is the preferred design for the reasons just cited.

The following sections define events and describe the roles of sources and listeners.


Events

In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples.

Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. You are free to define events that are appropriate for your application.


Event Sources

A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form:

      public void addTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.

Some sources may allow only one listener to register. The general form of such a method is this:

      public void addTypeListener(TypeListener el)
          throws java.util.TooManyListenersException

Here, Type is the name of the event and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this:

      public void removeTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners.


Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface. Many other listener interfaces are discussed later in this and other chapters.


Sources of Events

Table 20-2 lists some of the user interface components that can generate the events described in the previous section. In addition to these graphical user interface elements, other components, such as an applet, can generate events. For example, you receive key and mouse events from an applet. (You may also build your own components that generate events.) In this chapter we will be handling only mouse and keyboard events.


Event Source Examples

Button:  Generates action events when the button is pressed.

Checkbox:  Generates item events when the check box is selected or deselected.

Choice:  Generates item events when the choice is changed.

List:  Generates action events when an item is double-clicked; generates item events when an item is selected or deselected.

Menu Item:  Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected.

Scrollbar:  Generates adjustment events when the scroll bar is manipulated.

Text components:  Generates text events when the user enters a character.

Window:  Generates window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.





Event Listener Interfaces

As explained, the delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Lists commonly used listener interfaces and provides a brief description of the methods that they define. The following sections examine the specific methods that are contained in each interface.


Commonly Used Event Listener Interfaces

ActionListener:  Defines one method to receive action events.

AdjustmentListener:  Defines one method to receive adjustment events.

ComponentListener:  Defines four methods to recognize when a component is hidden, moved, resized, or shown.

ContainerListener:  Defines two methods to recognize when a component is added to or removed from a container.

FocusListener:  Defines two methods to recognize when a component gains or loses keyboard focus.

ItemListener:  Defines one method to recognize when the state of an item changes.

KeyListener:  Defines three methods to recognize when a key is pressed, released, or typed.

MouseListener:  Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released.

MouseMotionListener:  Defines two methods to recognize when the mouse is dragged or moved.

MouseWheelListener:  Defines one method to recognize when the mouse wheel is moved. (Added by Java 2, version 1.4)

TextListener:  Defines one method to recognize when a text value changes.

WindowFocusListener:  Defines two methods to recognize when a window gains or loses input focus. (Added by Java 2, version 1.4)

WindowListener:  Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.


The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown here:

      void actionPerformed(ActionEvent ae)


The AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment event occurs. Its general form is shown here:

      void adjustmentValueChanged(AdjustmentEvent ae)


The ComponentListener Interface
This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. Their general forms are shown here:

      void componentResized(ComponentEvent ce)
      void componentMoved(ComponentEvent ce)
      void componentShown(ComponentEvent ce)
      void componentHidden(ComponentEvent ce)

The AWT processes the resize and move events. The componentResized( ) and componentMoved( ) methods are provided for notification purposes only.


The ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded( ) is invoked. When a component is removed from a container, componentRemoved( ) is invoked. Their general forms are shown here:

      void componentAdded(ContainerEvent ce)
      void componentRemoved(ContainerEvent ce)


The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is invoked. When a component loses keyboard focus, focusLost( ) is called. Their general forms are shown here:

      void focusGained(FocusEvent fe)
      void focusLost(FocusEvent fe)


The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is shown here:

      void itemStateChanged(ItemEvent ie)


The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered.

For example, if a user presses and releases the A key, three events are generated in sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released.

The general forms of these methods are shown here:

      void keyPressed(KeyEvent ke)
      void keyReleased(KeyEvent ke)
      void keyTyped(KeyEvent ke)


The MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:

      void mouseClicked(MouseEvent me)
      void mouseEntered(MouseEvent me)
      void mouseExited(MouseEvent me)
      void mousePressed(MouseEvent me)
      void mouseReleased(MouseEvent me)


The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here:

      void mouseDragged(MouseEvent me)
      void mouseMoved(MouseEvent me)


The MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved. Its general form is shown here.

      void mouseWheelMoved(MouseWheelEvent mwe)

MouseWheelListener was added by Java 2, version 1.4.


The TextListener Interface
This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text field. Its general form is shown here:

      void textChanged(TextEvent te)


The WindowFocusListener Interface
This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called when a window gains or losses input focus. Their general forms are shown here.

      void windowGainedFocus(WindowEvent we)
      void windowLostFocus(WindowEvent we)

WindowFocusListener was added by Java 2, version 1.4.


The WindowListener Interface
This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed. The general forms of these methods are

      void windowActivated(WindowEvent we)
      void windowClosed(WindowEvent we)
      void windowClosing(WindowEvent we)
      void windowDeactivated(WindowEvent we)
      void windowDeiconified(WindowEvent we)
      void windowIconified(WindowEvent we)
      void windowOpened(WindowEvent we)

No comments:

Post a Comment