Event Handling in Java

Event Handling in Java with Examples

In this article, I am going to discuss Event Handling in Java with Examples. Please read our previous article, where we discussed AWT Controls in Java. This chapter examines a crucial aspect of Java: the event. At the end of this article, you will understand the following pointers in detail.

  1. What is Event Handling in Java?
  2. Why do we need Event Handling in Java?
  3. Two Event Handling Mechanisms.
  4. The Delegation Event Model in Java
  5. Advantage of using Delegation Event Model
  6. Components of Event Handling
  7. Steps to handle an event in java
  8. Event Classes
  9. Sources of Events
Event Handling in Java:

Event handling is prime to Java programming because it’s integral to the creation of applets and other sorts of GUI-based programs. Events are supported by a variety of packages, including java.util, java.awt, and java.awt.event. The program response is generated when the user interacts with a GUI-based program.

Two Event Handling Mechanisms in Java
  1. Original Version of Java (1.0)
  2. Modern Versions of Java, beginning with Java version 1.1

The way during which events are handled changed significantly between the first version of Java (1.0) and every one subsequent version of Java, beginning with version 1.1. Although the 1.0 method of event handling remains supported, it’s not recommended for brand spanking new programs.

Also, many of the methods that support the old 1.0 event model are deprecated. The modern approach is the way that events should be handled by all-new programs.

The Delegation Event Model

The modern approach to handling events is predicated on the delegation event model, which defines standard and consistent mechanisms to get and process events. Its concept is sort of simple: a source generates an occasion and sends it to at least one or more listeners. In this scheme, the listener simply waits until it receives an occasion. Once an occasion is received, the listener processes the event then returns.

The Delegation Event Model

Using the delegation event model is actually quite easy. Just follow these two steps:

  1. Implement the appropriate interface in the listener so that it will receive the type of event desired.
  2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.
Advantage of using Delegation Event Model

The advantage of this design is that the appliance logic that processes events is cleanly separated from the interface logic that generates those events. An interface element is in a position to “delegate” the processing of an occasion to a separate piece of code. In the delegation event model, listeners must register with a source so as to receive an occasional notification. This provides is a crucial benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events.

Note: Java also allows you to process events without using the delegation event model. This can be done by extending an AWT component.

Components of Event Handling

1. Events

An event is an object that describes a phase change during a source. It is often generated as a consequence of an individual interacting with the weather during a graphical interface. Some activities that cause events to be generated are pressing a button, entering a personality via the keyboard, selecting an item during a list, and clicking the mouse. Events can also occur that aren’t directly caused by interactions with an interface. For example, an occasion could also be generated when a timer expires, a counter exceeds a worth, a software or hardware failure occurs, or an operation is completed.

2. Event Sources

A source is an object that generates an occasion. This occurs when the interior state of that object changes in how. Sources may generate quite one sort of event. A source must register listeners so as for the listeners to receive notifications a few specific sorts of events. Each sort of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)

Here, Type is that the name of the event and el may be a regard to the event listener.

3. Event Listeners

A listener is an object that’s notified when an occasion occurs. It has two major requirements. First, it registered with one or more sources to receive notifications about specific sorts of events. Second, it implements methods to receive and process these notifications. The methods that receive and process events are defined in interfaces found in java.awt.event.

Event Handling in Java

Steps to handle an event
  1. Whenever the user clicks the button an event is generated.
  2. Now the object of concerned event class will be automatically created and information about the source and the event gets populated with in the same object.
  3. Then the event object is forwarded to the method of registered listener class.
  4. Now the method will get executed and returns.
Sample Program to demonstrate Event Handling in Java
import java.awt.*;
import java.awt.event.*;

class EventHandling extends Frame implements ActionListener
{
    TextField textField;

    EventHandling ()
    {
        textField = new TextField ();
        textField.setBounds (60, 50, 170, 20);
        Button button = new Button ("Show");
        button.setBounds (90, 140, 75, 40);

        button.addActionListener (this);
        add (button);
        add (textField);
        setSize (250, 250);
        setLayout (null);
        setVisible (true);
    }


    public void actionPerformed (ActionEvent e)
    {
        textField.setText ("Hello World");
    }

    public static void main (String args[])
    {
        new EventHandling ();
    }
}

Output:

Program to demonstrate Event Handling in Java

Event Classes

The classes that represent events ae at the core of Java’s event handling mechanism. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events.

The ActionEvent Class

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. It defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. There is also an integer constant, ACTION_ PERFORMED, which can be used to identify action events.

Constructors

  1. ActionEvent(Object src, int type, String cmd)
  2. ActionEvent(Object src, int type, String cmd, int modifiers)
  3. ActionEvent(Object src, int type, String cmd, long when, int modifiers)

Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd.

Methods
  1. String getActionCommand(): It is used to obtain the command name for the invoking ActionEvent object.
  2. int getModifiers(): It returns a value that indicates which modifier keys (ALT, CTRL, META, and /or SHIFT) were pressed when the event was generated.
  3. long getwhen(): It returns the time at which the event took place. This is called the event’s timestamp.
The AdjustmentEvent Class

An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustmentEvent class defines integer constants that can be used to identify them. The constants are BLOCK_DECREMENT, BLOCK_INCREMENT, TRACK, UNIT_DECREMENT, UNIT_INCREMENT, and ADJUSTMENT_VALUE_CHANGED.

Constructor

AdjustmentEvent(Adjustable src, int id, int type, int data)

Here, src is a reference to the object that generated this event. The id specifies the event. The type of adjustment is specified by type, and its associated data is data.

Methods
  1. Adjustable getAdjustable(): It returns the object that generated the event.
  2. int getAdjustmentType(): It is used to obtain the type of adjustment event.
  3. Component getChild(): It returns a reference to the component that was added to or removed from the container.
The ComponentEvent Class

A ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four types of component events. The ComponentEvent class defines integer constants that can be used to identify them. The Constants are COMPONENT_HIDDEN, COMPONENT_MOVED, COMPONENT_RESIZED, and COMPONENT_SHOWN. ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent.

Constructor

ComponentEvent(Component src, int type)

Here, src is a reference to the object that generated this event. The type of event is specified by the type.

Method

Component getComponent() : It returns the component that generated the event.

The ContainerEvent Class

ContainerEvent is a subclass of ComponentEvent. A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.

Constructor

ConstructorEvent(Component src, int type, Component comp)

Here, src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp.

Methods
  1. Container getContainer(): It is used to obtain a reference to the container that generates this event.
  2. Container getChild(): It returns a reference to the component that was added to or removed from the container.
The FocusEvent Class

FocusEvent is a subclass of ComponentEvent. A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.

Constructors
  1. FocusEvent(Component src, int type)
  2. FocusEvent(Component src, int type, boolean temporaryFlag)
  3. FocusEvent(Component src, int type, boolean temporaryFlag, Component other)

Here, src is a reference to the component that generated this event. The type of event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. The other component involved in the focus change, called the opposite component, is passed in other. Therefore, if a FOCUS_GAINED event occurred, others will refer to the component that lost focus. Conversely, if a FOCUS_LOST event occurred, others will refer to the component that gains focus.

Methods
  1. Component getOppositeComponent( ) : It is used to determine the other component.
  2. boolean isTemporary(): It indicates if this focus change is temporary. The method returns true if the change is temporary. Otherwise, it returns false.
The InputEvent Class

The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are KeyEvent and MouseEvent. InputEvent defines several integer constants that represent any modifiers, such as the control key being pressed, that might be associated with the event.

Methods

To test if a modifier was pressed at the time an event is generated, use following methods:

  1. boolean isAltDown( )
  2. boolean isAltGraphDown( )
  3. boolean isControlDown( )
  4. boolean isMetaDown( )
  5. boolean isShiftDown( )
  6. int getModifiers( ) : It is used to obtain a value that contains all of the original modifier flags.
  7. int getModifiersEx( ) : It is used to obtain the extended modifiers.
The ItemEvent Class

AnItemEventisgeneratedwhenacheckboxoralistitemisclickedorwhenacheckablemenu item is selected or deselected. There are two types of item events, which are identified by the following integer constants: DESELECTED and SELECTED.

Constructor

ItemEvent(ItemSelectable src, int type, Object entry, int state)

Here, src is a reference to the component that generated this event. The type of event is specified by type. The specific item that generated the item event is passed in the entry. The current state of that item is in the state.

Methods
  1. Object getItem(): It can be used to obtain a reference to the item that generated an event.
  2. ItemSelectable getItemSelectable( ): It can be used to obtain a reference to the ItemSelectable object that generated an event.
  3. int getStateChange( ): It returns the state change (that is, SELECTED or DESELECTED) for the event.
The KeyEvent Class

A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. KeyEvent is a subclass of InputEvent.

Constructor

KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.

Methods
  1. char getKeyChar( ) : It returns the character that was entered.
  2. int getKeyCode( ) : It returns the key code.
The MouseEvent Class

MouseEvent is a subclass of InputEvent. There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED, MOUSE_DRAGGED, MOUSE_ENTERED, MOUSE_EXITED, MOUSE_MOVED, MOUSE_PRESSED, MOUSE_RELEASED and MOUSE_WHEEL.

Constructor

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)

Here, src is a reference to the component that generated the event. The type of event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

Methods
  1. int getX(): It returns the X coordinates of the mouse within the component when the event occurred.
  2. int getY(): It returns the Y coordinates of the mouse within the component when the event occurred.
  3. Point getPoint( ): It returns a Point object that contains the X, Y coordinates in its integer members: x and y.
  4. void translatePoint(int x, int y): It changes the location of the event.
  5. int getClickCount( ): It obtains the number of mouse clicks for this event.
  6. boolean isPopupTrigger( ): It tests if this event causes a pop-up menu to appear on this platform.
  7. int getButton( ): It returns a value that represents the button that caused the event. The return value will be one of these constants defined by MouseEvent: NOBUTTON, BUTTON1, BUTTON2, and BUTTON3.
The MouseWheelEvent Class

The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of MouseEvent. Not all mice have wheels. If a mouse has a wheel, it is located between the left and right buttons. Mouse wheels are used for scrolling. MouseWheelEvent defines these two integer constants: WHEEL_BLOCK_SCROLL and WHEEL_UNIT_SCROLL.

Constructor

MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup, int scrollHow, int amount, int count)

Here, src is a reference to the object that generated the event. The type of event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when the event occurred. The coordinates of the mouse are passed in x and y. The number of clicks the wheel has rotated is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform. The scrollHow value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_ SCROLL. The number of units to scroll is passed in amount. The count parameter indicates the number of rotational units that the wheel moved.

Methods
  1. int getWheelRotation( ): It defines methods that give you access to the wheel event.
  2. int getScrollType( ): It is used to obtain the type of scroll. It returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
  3. int getScrollAmount(): If the scroll type is WHEEL_UNIT_SCROLL, you can obtain the number of units to scroll by calling getScrollAmount( ).
The TextEvent Class

Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.

Constructor

TextEvent(Object src, int type)

Here, src is a reference to the object that generated this event. The type of event is specified by type.

The WindowEvent Class

There are ten types of window events. The WindowEvent class defines integer constants that can be used to identify them. The constants are shown here: WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_DEACTIVATED, WINDOW_DEICONIFIED, WINDOW_GAINED_FOCUS, WINDOW_ICONIFIED, WINDOW_LOST_FOCUS, WINDOW_OPENED and WINDOW_STATE_CHANGED.

Constructor
  1. WindowEvent(Window src, int type)
  2. WindowEvent(Window src, int type, Window other)
  3. WindowEvent(Window src, int type, int fromState, int toState)
  4. WindowEvent(Window src, int type, Window other, int fromState, int toState)

Here, src is a reference to the object that generated this event. The type of event is type. other specifies the opposite window when a focus or activation event occurs. The fromState specifies the prior state of the window, and toState specifies the new state that the window will have when a window state change occurs.

Methods
  1. Window getWindow( ): It returns the Window object that generated the event.
  2. Window getOppositeWindow( ): It return the opposite window.
  3. int getOldState( ): It returns the previous window state.
  4. int getNewState( ): It returns the current window state.
Sources of Events

Below 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, any class derived from Component, such as Applet, can generate events. For example, you can receive key and mouse events from an applet.

  1. Button: It is used to generate action events when the button is pressed.
  2. Checkbox: It is used to generate item events when the checkbox is selected or deselected.
  3. Choice: It is used to generate item events when the choice is changed.
  4. List: It is used to generate action events when an item is double-clicked and generates item events when an item is selected or deselected.
  5. Menu item: It is used to generate action events when a menu item is selected and generates item events when a checkable menu item is selected or deselected.
  6. Scroll bar: It is used to generate adjustment events when the scroll bar is manipulated.
  7. Text Components: It is used to generate text events when the user enters a character.
  8. Window: It is used to generates window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

In the next article, I am going to discuss Event Listener Interfaces in Java with examples. Here, in this article, I try to explain Event Handling in Java with Example and I hope you enjoy this Event Handling in Java with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *