- Event Handling in Java Complete Tutorial
- Event Handling in Java
- Java Event classes and Listener interfaces
- Components of Event Handling
- Events
- Events Source
- Listeners
- Process of Event Handling in Java
- Steps to perform Event Handling
- Registration Methods
- Java Event Handling Code
- Example : Event handling in Java by implementing ActionListener inside the class
- Example : Event handling in Java by implementing ActionListener outside the class
- Example : Event handling by implementing ActionListener in anonymous class
- Conclusion
- Newsletter Updates
- Newsletter
- Recent Posts
- Event Handling in Java
- What is Event Handling in Java?
- Events in Java
- How are Events Handled?
- Event Handling in Java Example
- Components of Event Handling in Java
- 1. Event Handler
- 2. Event Sources
- 3. Event Listeners
- Event Classes and Listener Interfaces in Java
- Steps to Perform Event Handling in Java
- Java Event Handling Code
- Within Class
- Other Class
- Anonymous Class
- Conclusion
Event Handling in Java Complete Tutorial
Event handling in Java is one of the important topic. It is asked in many java professional interviews and it is very necessary for developers to learn.
When state of an object is changed, it is known as an event in Java.
For example : button click , mouse hover etc.
In Java, there are several event classes present and there are several Listener interfaces available for event handling.
All these event classes and listeners are present in java.awt.event package.
Event Handling in Java
Event Handling is managed by below mentioned aspects :
Let’s learn each in detail :
Java Event classes and Listener interfaces
Below are the list of event classes and listener interface present in Java :
Event Class | Listener Interface |
---|---|
MouseEvent | MouseListener MouseMotionListener |
KeyEvent | KeyListener |
MouseWheelEvent | MouseWheelListener |
ActionEvent | ActionListener |
TextEvent | TextListener |
WindowEvent | WindowListener |
ContainerEvent | ContainerListener |
ComponentEvent | ComponentListener |
AdjustmentEvent | AdjustmentListener |
FocusEvent | FocusListener |
ItemEvent | ItemListener |
Components of Event Handling
There are three components in Event Handling , as mentioned below :
Events
As discussed earlier, Events are simply change in state of object in java.
Events Source
Event Source is that object which generates the event. Some Event Source examples are : button, text field etc.
Listeners
Listener listens to event. It is an object as well. Whenever an event occurs, listeners gets notified.
Process of Event Handling in Java
An event source generates the event. Event source send it to the registered listeners,
As listener receives the event, it process the event and then return it.
Steps to perform Event Handling
Below are the major steps in performing event handling :
Registration Methods
We need to register the component with the listener to perform event handling.
This can be done using registration methods provided by many classes :
Class name | Method |
---|---|
Button | public void addActionListener(ActionListener a)<> |
TextField | 1) public void addActionListener(ActionListener a)<> 2) public void addTextListener(TextListener a)<> |
CheckBox | public void addItemListener(ItemListener a)<> |
List | 1) public void addActionListener(ActionListener a)<> 2) public void addItemListener(ItemListener a)<> |
MenuItem | public void addActionListener(ActionListener a)<> |
Choice | public void addItemListener(ItemListener a)<> |
TextArea | public void addTextListener(TextListener a)<> |
Java Event Handling Code
Event Handling code can be placed in below mentioned places :
Example : Event handling in Java by implementing ActionListener inside the class
package eventHandling; import java.awt.*; import java.awt.event.*; public class EventApp extends Frame implements ActionListener < TextField field; EventApp() < //creating components in the constructor field = new TextField(); field.setBounds(60, 50, 170, 20); Button button = new Button("submit"); button.setBounds(100, 120, 80, 30); //registering the listener //pass the current instance using 'this' button.addActionListener(this); //adding components //setting size, layout and visibility add(field); add(button); setSize(300, 300); setLayout(null); setVisible(true); >public void actionPerformed(ActionEvent e) < field.setText("You clicked the button"); >public static void main(String args[]) < new EventApp(); >>
Example : Event handling in Java by implementing ActionListener outside the class
package eventHandling; import java.awt.*; import java.awt.event.*; class EventApp2 extends Frame < TextField field; EventApp2() < // creating components in the constructor field = new TextField(); field.setBounds(60, 50, 170, 20); Button button = new Button("click me"); button.setBounds(100, 120, 80, 30); //registering the listener // pass the current instance using 'this' MainClass main = new MainClass(this); button.addActionListener(main); //adding components //setting size, layout and visibility add(b); add(field); setSize(300, 300); setLayout(null); setVisible(true); >public static void main(String args[]) < new EventApp2(); >>
package eventHandling; import java.awt.event.*; class MainClass implements ActionListener < EventApp2 obj; MainClass(EventApp2 obj) < this.obj = obj; >public void actionPerformed(ActionEvent e) < obj.field.setText("You clicked the button"); >>
Example : Event handling by implementing ActionListener in anonymous class
package eventHandling; import java.awt.*; import java.awt.event.*; public class EventApp3 extends Frame < TextField field; EventApp3() < field = new TextField(); field.setBounds(60, 50, 170, 20); Button button = new Button("click. "); button.setBounds(50, 120, 80, 30); button.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < field.setText("Helloooo"); >>); add(button); add(field); setSize(300, 300); setLayout(null); setVisible(true); > public static void main(String args[]) < new EventApp3(); >>
Further Readings:
Conclusion
Event Handling in Java is very important mechanism.
It is the process of handling events in Java. Events are simply change of state of objects.
The management and listening of these events is known as Event Handling.
Newsletter Updates
Enter your name and email address below to subscribe to our newsletter
Newsletter
Recent Posts
- How to Iterate over a List in Thymeleaf 17th March 2022
- How to Loop through Map in Thymeleaf 16th March 2022
- Complete Guide on using Thymeleaf with Spring Boot 25th February 2022
- What is MapReduce in Hadoop? 29th January 2022
- How to Export Data into Excel in Spring Boot Application 17th January 2022
Event Handling in Java
Event handling in Java is the procedure that controls an event and performs appropriate action if it occurs. The code or set of instructions used to implement it is known as the Event handler .
It consists of two major components:
The source is the object where the event occurs, and the event listener is responsible for taking appropriate actions when an event occurs. These Listeners must be registered with the source object in order for the listener to receive event notifications.
What is Event Handling in Java?
Many event listeners are frequently used; recall the click of a button that takes you to another website or the mouse scroll? All of this is accomplished through the use of various event handlers, and the mechanism is known as event handling.
Events in Java
Events in Java represent the change in the state of any object. Events occur when the user interacts with the interface. Clicking a button, moving the mouse, typing a character, selecting an item from a list, and scrolling the page are all examples of behaviors that cause an event to occur.
Types of Events in Java:
- Foreground Events: These events necessitate the user’s direct participation. They are produced as a result of a user interacting with graphical components in a Graphical User Interface.
- Background Events: Background events are those that require end-user interaction. Operating system interrupts and hardware or software failures are examples of background events.
Event handling in Java is the process of controlling an event and taking appropriate action if one occurs.
How are Events Handled?
The modern approach to event processing is based on the Delegation Model. It defines a standardized and compatible mechanism for generating and processing events. In this approach, a source generates an event and sends it to one or more listeners. The listener sits and waits for an event to occur. When it gets an event, it is processed by the listener and returned. The user interface elements can delegate the processing of an event to a different function.
The image below shows the flow chart of the event delegation model.
Event Handling in Java Example
The example below shows how you can handle events in Java. In this example, we will create a frame using Java and add a button. Once the interface is created, we will add one event listener to the button, which will change the background and foreground (text) color on click. Another event listener is activating dispose of the frame, that is, the x button on the top-right of the frame.
Output: The initial output of the program is the user interface that we discussed above.
Now, once you click on the click me button, the font, font color, and background color for the button are shown in the image below.
Components of Event Handling in Java
An Event Model is fundamentally composed of the three elements listed below:
In the subsequent sections, we will go over each one in-depth.
1. Event Handler
An event handler is a function or method that executes program statements in response to an event. A software program that processes activities such as keystrokes and mouse movements is what an event handler is. Event handlers in Web sites make Web content dynamic.
2. Event Sources
An object on which an event occurs is referred to as a source. The source is in charge of informing the handler about the event that occurred. There are various sources like buttons, checkboxes, lists, menu-item, choices, scrollbars, text components, windows, etc.
3. Event Listeners
When an event occurs, an object named an event listener is called. The listeners need two things: first, they must be registered with a source; however, they can be registered with multiple sources to receive event notifications.
Second, it must put in place the methods for receiving and processing notifications. A set of interfaces defines the methods for dealing with events. The Java.awt.event package contains the following event classes and interfaces.
Event Classes and Listener Interfaces in Java
Event Classes | Description | Listener Interface |
---|---|---|
ActionEvent | When a button is clicked or a list item is double-clicked, an ActionEvent is triggered. | ActionListener |
MouseEvent | This event indicates a mouse action occurred in a component | MouseListener |
KeyEvent | The Key event is triggered when the character is entered using the keyboard. | KeyListener |
ItemEvent | An event that indicates whether an item was selected or not. | ItemListener |
TextEvent | when the value of a textarea or text field is changed | TextListener |
MouseWheelEvent | generated when the mouse wheel is rotated | MouseWheelListener |
WindowEvent | The object of this class represents the change in the state of a window and are generated when the window is activated, deactivated, deiconified, iconified, opened or closed | WindowListener |
ComponentEvent | when a component is hidden, moved, resized, or made visible | ComponentEventListener |
ContainerEvent | when a component is added or removed from a container | ContainerListener |
AdjustmentEvent | when the scroll bar is manipulated | AdjustmentListener |
FocusEvent | when a component gains or loses keyboard focus | FocusListener |
Steps to Perform Event Handling in Java
The following steps are required to perform event handling in Java:
Implement appropriate interface in the class: The first step is to implement an appropriate interface in the class. For the example we used above, this step can be the implementation of frame and mybtn objects, i.e. simply creating them.
This code shows how we created frames and buttons and added buttons to the frame.
Register the component with the listener: Once we are done with the implementation of the interface in the class, the second step is to register the created components with listeners, which can be done using inbuilt functions. In our example, we added two event listeners.
- We registered our frame object with the windows listener and commanded it to dispose of the frame on interaction.
Java Event Handling Code
Within Class
The code below demonstrates how event handling can be implemented in a single class. In this example, we’ll make a user interface with a button and a text field inside a frame, and we’ll handle the button’s click event so that the text inside the text field appears when you click the button.
- Firstly we created a class named MyClass that extends the inbuilt Frame class in Java and implements the ActionListner interface.
- Then created a text field object and inside the constructor of the class initialize it to a new empty textfield and set the bounds for it.
- Then the button is created and added and ActionListner passes the current instance of it.
- Then both of them are added to the extended frame and our UI is ready.
- Now we manipulate the abstract actionPerformed method, to make a response for the ActionListner added above, we command it to display «Hello» in the text field.
- Then we created an object of MyClass and the output is performed accordingly.
Output
Other Class
The same example of event handling in Java can be implemented using another class, the code for the same is given below.
- We created the same UI, we used in the previous example using the same approach.
- The only difference is that we used another class named Outer class which creates the object of MyClass and overrides the actionPerformed function for this object.
- The output of this is exactly the same as that of the previous example
Anonymous Class
Another way of creating an event handling programme in Java is using anonymous class implementation. The code below shows how you can implement using an anonymous class.
The benefit of using anonymous class implementation is that we don’t have to explicitly create another class to implement the actionPerformed method as we did in the previous example.
- Firstly we created the UI similar to the previous two examples, inside the class named MyClass which extends the Frame class in Java.
- Once we have created the text field and button objects, we added the same ActionListner to the button object using anonymous class implementation.
- Here we can override the actionPerfomed method, instead of manipulating it separately inside the same class or in another class.
- The output is the same as that of the previous two examples.
Conclusion
- We have covered the basics of event handling in Java along with its implementation techniques.
- Event handling in Java is controlling an event and taking appropriate action if one occurs. Events handling makes web pages and mobile applications live.