In this article we will learn what is event handling and how to handle events in Java programs using the delegation event model.
Event handling in Java programming refers to the process of responding to events that occur in a graphical user interface (GUI) or other user interface (UI) elements. Events can include user actions such as clicking a button, selecting a menu item, or pressing a key. In Java, event handling is implemented using event listeners and event handlers.
Event listeners are objects that “listen” for specific events to occur and are notified when they do. Event handlers are methods or blocks of code that are executed when a specific event occurs. To implement event handling in Java, you will typically create event listeners and register them with the UI elements that you want to respond to events on. Then, when the events occur, the appropriate event handlers will be called to handle them.
Java provides a number of built-in event listeners and event handlers for common UI elements such as buttons and text fields. Additionally, the Java Standard Widget Toolkit (SWT) provides additional event listeners and handlers for more advanced UI elements.
The delegation event model is a common method for handling events in Java. It is based on the idea that when an event occurs, it is delegated or passed on to an appropriate event handler for processing. This model separates the definition of the event from the handling of the event, allowing for more flexibility and reuse in your code.
In the delegation event model, events are typically handled by one or more event listeners. An event listener is an object that implements a specific interface and can be registered with a UI component to receive notification of events. For example, in the case of a button, the button would be the source of the event and an event listener, such as an action listener, would be registered with the button to receive notification when the button is clicked.
To handle an event in a Java program using the delegation event model, you must first create an event listener that implements the appropriate interface for the type of event you want to handle. For example, to handle a button click event, you would create an action listener. Next, you must register the event listener with the appropriate UI component. This is typically done by calling a method on the UI component that accepts the event listener as a parameter.
When the event occurs, the event listener’s method will be called by the event source, passing in an event object that contains information about the event. The event listener can then use the information in the event object to determine how to handle the event.
In summary, event handling in Java using the delegation event model involves the following steps:
- Create an event listener that implements the appropriate interface for the event you want to handle.
- Register the event listener with the appropriate UI component.
- When the event occurs, the event listener’s method will be called and passed an event object.
- The event listener can use the information in the event object to determine how to handle the event.
Delegation Event Model
The delegation event model is a common method for handling events in Java, it separates the definition of an event from the handling of an event. This allows for more flexibility and reuse in the code.
The delegation event model uses interfaces and classes to handle events. Interfaces define methods that must be implemented by classes that want to handle specific types of events. For example, the ActionListener interface defines the actionPerformed method that must be implemented by any class that wants to handle action events.
Here is an example of how to handle a button click event using the delegation event model:
Create an event listener class that implements the appropriate interface for the event you want to handle. In this case, we will create a class called MyButtonListener that implements the ActionListener interface:
1 2 3 4 5 6 7 | class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button was clicked!"); } } |
Create an instance of the event listener and register it with the button:
1 2 3 4 5 6 | JButton button = new JButton("Click Here"); button.setPreferredSize(new Dimension(150, 100)); MyButtonListener listener = new MyButtonListener(); button.addActionListener(listener); |
Add the button to a container, such as a JFrame, and make the frame visible:
1 2 3 4 5 6 7 8 9 10 11 | //Frame JFrame jFrame = new JFrame("Button Event"); jFrame.setLayout(new FlowLayout()); jFrame.setSize(500, 360); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add button to frame jFrame.add(button); jFrame.setVisible(true); |
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Main { private static void createAndShowGUI() { JButton button = new JButton("Click Here"); button.setPreferredSize(new Dimension(150, 100)); MyButtonListener listener = new MyButtonListener(); button.addActionListener(listener); //Frame JFrame jFrame = new JFrame("Button Event"); jFrame.setLayout(new FlowLayout()); jFrame.setSize(500, 360); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add button to frame jFrame.add(button); jFrame.setVisible(true); } public static void main(String[] args) { createAndShowGUI(); } } class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button was clicked!"); } } |
When the user clicks the button, the actionPerformed method of the MyButtonListener class will be called, which will print “Button was clicked!” to the console.
This example demonstrates how to handle a button click event using the delegation event model in Java. It creates an event listener class, MyButtonListener, that implements the ActionListener interface, and registers an instance of that class with a JButton. When the button is clicked, the actionPerformed method of the listener is called, providing a way to handle the event.
Another advantage of this model is, notification of events is sent only to the registered listeners.
Events
Events are actions or occurrences that can be detected by a program. They are a way to communicate that something has happened, and they are used in event-driven programming. Events can be generated by a variety of sources, including user actions, system activities, or external conditions.
In a graphical user interface (GUI) program, events can include user actions such as clicking a button, selecting a menu item, or pressing a key. Events can also be generated by the system, such as a timer expiring or a network connection being established.
In Java, events are typically handled using the delegation event model, which separates the definition of an event from the handling of an event. This allows for more flexibility and reuse in the code. When an event occurs, it is passed on to an appropriate event handler for processing.
Java provides a number of built-in events for common UI elements such as buttons, text fields, and menu items. Additionally, the Java Standard Widget Toolkit (SWT) provides additional events for more advanced UI elements.
Event handling in Java involves creating event listeners and registering them with the UI elements that you want to respond to events on. When the events occur, the appropriate event handlers will be called to handle them.
In summary, events are actions or occurrences that can be detected by a program, they are used in event-driven programming, they can be generated by a variety of sources such as user actions, system activities, or external conditions, and in Java they are typically handled using the delegation event model.
Event Sources
In event-driven programming, an event source is an object that generates an event. Examples of event sources in a graphical user interface (GUI) program include buttons, check boxes, radio buttons, text boxes, and many other UI elements.
An event source can generate multiple types of events, each type of event is typically handled by a different type of event listener. For example, a button can generate both action events (when it is clicked) and focus events (when it receives or loses focus).
Event sources typically have methods for registering and unregistering event listeners. When an event occurs, the event source sends the event to all registered event listeners by calling a specific method on the listener, passing an event object that contains information about the event.
It is also important to note that event sources can be not only UI elements, but also other objects or systems. For example, a network connection, a sensor, a file system change, a timer, and many others can also be event sources.
In summary, an event source is an object that generates an event, it can generate multiple types of events, and it has methods for registering and unregistering event listeners, when an event occurs, the event source sends the event to all registered event listeners.
A source must be registered with listeners in order for the events to be detected. The general form of a registration method is as follows:
public void addTypeListener(TypeListener tl)
This is a method signature for adding a type of listener to an event source. The method takes a parameter of TypeListener, which is typically an interface or a class that implements the interface for a specific type of event.
The method is typically used to register an event listener with the event source. For example, if the event source is a button, the addTypeListener method would be used to register a listener for a specific type of event generated by that button, such as a button click.
The TypeListener parameter is an interface or a class that has a set of methods to handle the specific type of event. The class that implements this interface will be registered with the event source to listen for the specific event and take the appropriate action when the event occurs.
It is important to note that this is just a signature of a method and it can be implemented in different ways depending on the use case and the context, there can be different name, different parameter or even different return type.
Here’s an example of how the addTypeListener method might be used in a program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class MyButton extends JButton { private List<TypeListener> typeListeners = new ArrayList<TypeListener>(); public void addTypeListener(TypeListener tl) { typeListeners.add(tl); } public void removeTypeListener(TypeListener tl) { typeListeners.remove(tl); } private void fireTypeEvent() { TypeEvent event = new TypeEvent(this); for (TypeListener tl : typeListeners) { tl.handleTypeEvent(event); } } // other methods such as actionPerformed } class TypeListener { public void handleTypeEvent(TypeEvent e) { // code to handle the event } } |
In this example, MyButton is a class that extends the JButton class and adds the ability to handle TypeEvents. The class has an array list to hold the TypeListeners that are registered with the button. The addTypeListener method adds a TypeListener to the list, and the removeTypeListener method removes a TypeListener from the list. The fireTypeEvent method is called when the button generates a TypeEvent, it creates a TypeEvent object and passes it to each registered TypeListener’s handleTypeEvent method.
The TypeListener interface defines the handleTypeEvent method that must be implemented by any class that wants to handle TypeEvents.
Here’s an example of how the MyButton class might be used in a program:
1 2 3 4 5 | MyButton myButton = new MyButton(); TypeListener listener = new TypeListener(); myButton.addTypeListener(listener); |
In this example, an instance of the MyButton class is created, and an instance of the TypeListener class is created and registered with the button using the addTypeListener method. When the button generates a TypeEvent, the handleTypeEvent method of the TypeListener class will be called and the event will be handled.
This example demonstrates how to use the addTypeListener method to register a listener for a specific type of event with an event source. It also shows how the event source can generate the specific event and notify the registered listeners of the event.
public void removeTypeListener(TypeListener tl)
The removeTypeListener(TypeListener tl)
method is a method that is used to unregister or remove a specific listener from an event source. The method takes a parameter of TypeListener, which is typically an interface or a class that implements the interface for a specific type of event.
In the example provided above, the class MyButton has a list to hold the TypeListeners that are registered with the button and it allows to remove a specific TypeListener from that list using the removeTypeListener(TypeListener tl)
method.
It is important to note that, it is a best practice to always remove event listeners that are no longer needed, as it can help to avoid memory leaks and other performance issues.
Event Listeners
Event Listeners, in event-driven programming, are objects that “listen” for specific events to occur and are notified when they do. They are typically implemented using interfaces or abstract classes that define methods to handle specific types of events. Event listeners are registered with an event source, such as a button or a text field, to receive notification of events.
For example, when a button is clicked, the button generates an action event, which is passed to all registered action listeners. The listener’s actionPerformed method is called, providing a way to handle the event.
Event listeners are an important part of event-driven programming, as they allow the program to respond to events in a flexible and reusable way.
In Java, events and sources are maintained as classes, listeners are maintained as interfaces. Most of them are available in java.awt.event package.
Examples of listeners are MouseListener, Key Listener etc.
Here’s an example of an event listener in a Java program:
1 2 3 4 5 6 7 | class MyButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button was clicked!"); } } |
In this example, the class MyButtonListener implements the ActionListener interface, which defines the actionPerformed method that must be implemented by any class that wants to handle action events.
The actionPerformed method is called when the button is clicked, it provides a way to handle the event. In this case, it simply prints “Button was clicked!” to the console.
1 2 3 4 5 | JButton myButton = new JButton("Click me!"); MyButtonListener listener = new MyButtonListener(); myButton.addActionListener(listener); |
In this example, an instance of the JButton class is created, with the label “Click me!”. An instance of the MyButtonListener class is created and registered with the button using the addActionListener method. When the button is clicked, the actionPerformed method of the MyButtonListener class will be called, which will print “Button was clicked!” to the console.
This example demonstrates how to create an event listener in a Java program and how to register it with an event source. The listener class implements the appropriate interface for the event being handled, in this case, it is the ActionListener interface and it’s actionPerformed method is called when the event happens, providing a way to handle the event.
java.awt.event Package
The java.awt.event package contains many event classes which can be used for event handling.
Root class for all the event classes in Java is EventObject which is available in java.util package.
Root class for all AWT event classes is AWTEvent which is available in java.awt package and is a sub class of EventObject class.
Some of the frequently used event classes available in java.awt.eventpackage are listed below:
Various constructors and methods available in the above listed event classes are as follows:
ActionEvent
An action event is generated when a button is clicked, or a list item is double-clicked, or a menu item is selected.
ActionEvent class contains the following methods:
String getActionCommand() – Used to obtain the command name for the invoking ActionEvent object.
int getModifiers() – This method returns an integer that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed.
long getWhen() – Returns the time when the event was generated.
AdjustmentEvent
The adjustment event is generated when the scroll bar is adjusted. There are five types of adjustment events. For each type there is a constant declared in the class which are as follows:
BLOCK_DECREMENT
BLOCK_INCREMENT
TRACK
UNIT_DECREMENT
UNIT_INCREMENT
Following are the methods available in AdjustmentEvent class:
Adjustable getAdjustable() – Returns the object that generated the event.
int getAdjustmentType() – Returns one of the five constants that represents the type of event.
int getValue() – Returns a number that represents the amount of adjustment.
ComponentEvent
A component event is generated when the visibility, position and size of a component is changed. There are four types of component events which are identified by the following constants:
COMPONENT_HIDDEN
COMPONENT_SHOWN
COMPONENT_MOVED
COMPONENT_RESIZED
Following method is available in the ComponentEvent class:
Component getComponent() – Returns the component that generated the event.
ContainerEvent
A container event is generated when a component is added to or removed from the container. There are two types of container events which are represented by the following constants:
COMPONENT_ADDED
COMPONENT_REMOVED
Following are the methods available in the ContainerEvent class:
Container getContainer() – Returns the reference of the container that generated the event.
Component getChild() – Returns the reference of the component that is added to or removed from the container.
FocusEvent
A focus event is generated when a component gains or loses input focus. These events are identified by the following constants:
FOCUS_GAINED
FOCUS_LOST
Following are the methods available in the FocusEvent class:
Component getOppositeComponent() – Returns the other component that gained or lost focus.
boolean isTemporary() – Method returns true or false that indicates whether the change in focus is temporary or not.
ItemEvent
An item event is generated when the user clicks on a check box or clicks a list item or selects / deselects a checkable menu item. These events are identified by the following constants:
SELECTED
DESELECTED
Following are the methods available in the ItemEvent class:
Object getItem() – Returns a reference to the item whose state has changed.
ItemSelectable getItemSelectable() – Returns the reference of ItemSelectableobject that raised the event.
int getStateChange() – Returns the status of the state (whether SELECTED or DESELECTED)
KeyEvent
A key event is generated when a key on the keyboard is pressed, released or typed. These events are identified by the following constants:
KEY_PRESSED (when a key is pressed)
KEY_RELEASED (when a key is released)
KEY_TYPED (when a character is typed)
There are several other constants which recognizes various keys on the keyboard and they are as follows:
KeyEvent is a sub class of InputEvent. Following are the methods available in KeyEvent class:
char getKeyChar() – Returns the character entered from the keyboard
int getKeyCode() – Returns the key code
MouseEvent
Following are some of the methods available in MouseEvent class:
int getX() – Returns the x-coordinate of the mouse at which the event was generated.
int getY() – Returns the y-coordinate of the mouse at which the event was generated.
Point getPoint() – Returns the x and y coordinates of mouse at which the event was generated.
int getClickCount() – This method returns the number of mouse clicks for an event.
int getButton() – Returns an integer that represents the buttons that caused the event. Returned value can be either NOBUTTON, BUTTON1 (left mouse button), BUTTON2 (middle mouse button), or BUTTON3 (right mouse button).
Following methods are available to obtain the coordinates relative to the screen:
Point getLocationOnScreen()
int getXOnScreen()
int getYOnScreen()
Take your time to comment on this article.