Back to: Java Tutorials For Beginners and Professionals
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.
- What is Event Handling in Java?
- Why do we need Event Handling in Java?
- Two Event Handling Mechanisms.
- The Delegation Event Model in Java
- Advantages of using the Delegation Event Model
- Components of Event Handling
- Steps to handle an event in java
- Event Classes
- 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
- Original Version of Java (1.0)
- 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.
Event Delegation Model in Java
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 and then returns.
Using the delegation event model is actually quite easy. Just follow these two steps:
- Implement the appropriate interface in the listener so that it will receive the type of event desired.
- Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.
Advantages of using the 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, the Type is the name of the event and el may be a regard to the event listener.
3. Event Listeners in Java
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.
Steps to Handle Event in Java
- Whenever the user clicks the button an event is generated.
- Now the object of the concerned event class will be automatically created and information about the source and the event gets populated within the same object.
- Then the event object is forwarded to the method of the registered listener class.
- Now the method will get executed and returned.
Example 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:
Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. At the root of the Java event, the class hierarchy is EventObject, which is in java.util. It is the superclass for all events.
ActionEvent Class in Java
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.
ActionEvent Class Constructors in java
- ActionEvent(Object src, int type, String cmd)
- ActionEvent(Object src, int type, String cmd, int modifiers)
- 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.
ActionEvent Class Methods in Java
- String getActionCommand(): It is used to obtain the command name for the invoking ActionEvent object.
- int getModifiers(): It returns a value that indicates which modifier keys (ALT, CTRL, META, and /or SHIFT) were pressed when the event was generated.
- long getwhen(): It returns the time at which the event took place. This is called the event’s timestamp.
AdjustmentEvent Class in Java
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.
AdjustmentEvent Class Constructor in Java
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.
AdjustmentEvent Class Methods in Java
- Adjustable getAdjustable(): It returns the object that generated the event.
- int getAdjustmentType(): It is used to obtain the type of adjustment event.
- Component getChild(): It returns a reference to the component that was added to or removed from the container.
ComponentEvent Class in Java
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.
ComponentEvent Class Constructor in Java
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.
ComponentEvent Class Method in Java
Component getComponent(): It returns the component that generated the event.
ContainerEvent Class in Java
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.
ContainerEvent Class 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.
ContainerEvent Class Methods
- Container getContainer(): It is used to obtain a reference to the container that generates this event.
- Container getChild(): It returns a reference to the component that was added to or removed from the container.
FocusEvent Class in Java
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.
FocusEvent Class Constructors
- FocusEvent(Component src, int type)
- FocusEvent(Component src, int type, boolean temporaryFlag)
- 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 into another. 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.
FocusEvent Class Methods
- Component getOppositeComponent( ) : It is used to determine the other component.
- boolean isTemporary(): It indicates if this focus change is temporary. The method returns true if the change is temporary. Otherwise, it returns false.
InputEvent Class in Java
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.
InputEvent Class Methods
To test if a modifier was pressed at the time an event is generated, use following methods:
- boolean isAltDown( )
- boolean isAltGraphDown( )
- boolean isControlDown( )
- boolean isMetaDown( )
- boolean isShiftDown( )
- int getModifiers( ) : It is used to obtain a value that contains all of the original modifier flags.
- int getModifiersEx( ) : It is used to obtain the extended modifiers.
ItemEvent Class in Java
AnItemEventisgeneratedwhenacheckboxoralistitemisclickedorwhenacheckablemenu item is selected or deselected. There are two types of item events, which are identified by the following integer constants: DESELECTED and SELECTED.
ItemEvent Class 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.
ItemEvent Class Methods
- Object getItem(): It can be used to obtain a reference to the item that generated an event.
- ItemSelectable getItemSelectable( ): It can be used to obtain a reference to the ItemSelectable object that generated an event.
- int getStateChange( ): It returns the state change (that is, SELECTED or DESELECTED) for the event.
KeyEvent Class in Java
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.
KeyEvent Class 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, the code will contain VK_UNDEFINED.
KeyEvent Class Methods
- char getKeyChar( ) : It returns the character that was entered.
- int getKeyCode( ) : It returns the key code.
MouseEvent Class in Java
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.
MouseEvent Class 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.
MouseEvent Class Methods
- int getX(): It returns the X coordinates of the mouse within the component when the event occurred.
- int getY(): It returns the Y coordinates of the mouse within the component when the event occurred.
- Point getPoint( ): It returns a Point object that contains the X, Y coordinates in its integer members: x and y.
- void translatePoint(int x, int y): It changes the location of the event.
- int getClickCount( ): It obtains the number of mouse clicks for this event.
- boolean isPopupTrigger( ): It tests if this event causes a pop-up menu to appear on this platform.
- 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.
MouseWheelEvent Class in Java
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.
MouseWheelEvent Class 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.
MouseWheelEvent Class Methods
- int getWheelRotation( ): It defines methods that give you access to the wheel event.
- int getScrollType( ): It is used to obtain the type of scroll. It returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
- int getScrollAmount(): If the scroll type is WHEEL_UNIT_SCROLL, you can obtain the number of units to scroll by calling getScrollAmount( ).
TextEvent Class in Java
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.
TextEvent Class 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.
WindowEvent Class in Java
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.
WindowEvent Class Constructor
- WindowEvent(Window src, int type)
- WindowEvent(Window src, int type, Window other)
- WindowEvent(Window src, int type, int fromState, int toState)
- 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.
WindowEvent Class Methods
- Window getWindow( ): It returns the Window object that generated the event.
- Window getOppositeWindow( ): It return the opposite window.
- int getOldState( ): It returns the previous window state.
- 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 a Component, such as Applet, can generate events. For example, you can receive key and mouse events from an applet.
- Button: It is used to generate action events when the button is pressed.
- Checkbox: It is used to generate item events when the checkbox is selected or deselected.
- Choice: It is used to generate item events when the choice is changed.
- 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.
- 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.
- Scroll bar: It is used to generate adjustment events when the scroll bar is manipulated.
- Text Components: It is used to generate text events when the user enters a character.
- Window: It is used to generate 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 Examples and I hope you enjoy this Event Handling in Java with Examples article.
Very nice article. Explain everything in detail.