- 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
- Servlet – Event and Listener
- Event Categories
- Event Listener Interfaces
- Steps for Using Listeners
- Methods for Event Listeners and Related Classes
- Example
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
Servlet – Event and Listener
The term “event” refers to the occurrence of something. An event occurs when the state of an object changes. When these exceptions occur, we can conduct certain crucial actions, such as collecting total and current logged-in users, establishing database tables when deploying the project, building database connection objects, and so on. The javax.servlet and javax.servlet.http packages contain numerous Event classes and Listener interfaces.
The primary function of a Listener in a GUI application is to concentrate an event from a specific GUI component, handle it using Listener functions, and provide the response to the GUI application. The following technique is referred to as Event Handling or Event Delegation Model in GUI applications.
Event Categories
Servlet events are divided into two categories: high-level and low-level.
- Servlet context-level (application-level) event: This event concerns resources or states held at the appliance servlet context object’s extent.
- Session-level event: It involves resources or states associated with a sequence of requests from a single user session; in other words, it is associated with the HTTP session object.
There are two types of events on each of those two levels:
For each of the four-event categories, we can define one or more event listener classes. Multiple event categories can be monitored by a single listener class. Implementing an interface or interfaces from the javax.servlet package or javax.servlet.http package is a common way to make an occasion class.
Event Listener Interfaces
Steps for Using Listeners
If we want to utilize listener listeners in our web apps, we must follow the steps below:
Step 1: Get the Listener class ready.
Take one user-defined class, which must be a Listener interface implementation class. For instance, consider the public class Listener is implemented by MyListener
Step 2: In the web.xml file, configure the Listener class.
The following XML tags must be used in the web.xml file to configure the Listener class:
………… Name of the Listener class
Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned listener configuration.
Methods for Event Listeners and Related Classes
1) Methods for ServletContextListeners and the ServletContextEvent Class
The following methods are defined by ServletContextListener:
When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique shown below, which your listener might call:
ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be deleted, from which you may get any information you want.
2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class
ServletContextAttributeListener specifies the following methods:
The event class ServletContextAttributeEvent is used to notify about changes to the attributes of a web application’s servlet context. It includes the techniques listed below, which your listener can use:
- String getName() returns the name of the attribute that was added, deleted, or replaced as a string.
- Object getValue() is a method for retrieving the value of an attribute that has been added, deleted, or replaced. This method returns the previous value, not the new value, in the event of a replaced attribute.
3) Methods for HttpSessionListeners and the HttpSessionEvent Class
HttpSessionListener specifies the following methods:
When the session object is modified, HttpSessionEvent is informed. It includes the technique shown below, which your listener might call:
HttpSession getSession(): This function is used to obtain the generated or deleted session object.
4) Methods for HttpSessionAttributeListener and the HttpSessionBindingEvent Class
HttpSessionAttributeListener specifies the following methods:
When an object implements HttpSessionBindingListener is bound or freed from a session, HttpSessionBindingEvent is delivered to that object, or to a HttpSessionAttributeListener that has been set in the deployment descriptor when any attribute is bound, unbound, or replaced in a session. It includes the techniques listed below, which your listener can use:
- String getName(): returns the name of the attribute that was added, deleted, or replaced as a string.
- Object getValue(): is a method for retrieving the value of an attribute that has been added, deleted, or replaced. This method returns the previous value, not the new value, in the event of a replaced attribute.
- HttpSession getSession(): This method is used to obtain the session object whose attribute has changed.
Example
To demonstrate the servlet listener in action, let’s create a basic web application. In Eclipse, we’ll build a dynamic web project called ServletListenerExample, and the project structures will look like this.
The context init params and listener settings will be defined in web.xml. The class for database connectivity is DatabaseManager. The object will be added to the servlet context as an attribute. I’ll deal with the session, characteristics, and other things in MyServlet. We’ll use the AppContextListener to read the servlet context init parameters and use them to create the DatabaseManager object, which we’ll then set as an attribute on the ServletContext object. ServletContextAttributeListener is a simple implementation for logging the event when an attribute in the servlet context is added, removed, or replaced. HttpSessionListener is a simple implementation to log the event when the session is created or destroyed. ServletRequestListener is to log the servletRequest IP address when the request is initialized and destroyed.