Table of contents
1.
Introduction
2.
Classification of Events
3.
What is Event Handling in Java?
4.
Example
5.
Event Classes in Java
6.
Flow of Event Handling
7.
Code-Approaches
7.1.
Event Handling Within Class
7.2.
Event Handling by Other Class
7.3.
Event Handling by Anonymous Class
8.
Frequently Asked Questions
8.1.
What is the purpose of event handling in Java?
8.2.
What are the common event classes in Java?
8.3.
What are the different approaches to handle events in Java?
9.
Conclusion
Last Updated: Oct 24, 2024
Easy

Event Handling in Java

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Events are an essential part of Java programming. They allow programs to respond to user actions or system occurrences. In simple terms, an event is something that happens during the execution of a program. When an event occurs, the program can detect it & take appropriate action. 

Event Handling in Java

This article will discuss the basics of event handling in Java, which includes event types, classes, & different approaches to handling events. 

Classification of Events

In Java, events can be broadly classified into two categories: foreground events & background events.

Foreground events are those that require direct interaction from the user. These events are triggered by user actions such as clicking a button, pressing a key, or moving the mouse. Examples of foreground events include ActionEvent, MouseEvent, & KeyEvent. These events are handled by the event listeners that are registered on the corresponding GUI components.

On the other hand, background events occur without direct user interaction. These events are triggered by the system or the program itself. Examples of background events include TimerEvent, WindowEvent, & ComponentEvent. These events are used to perform tasks such as updating the GUI, monitoring system resources, or communicating with other programs.

What is Event Handling in Java?

Event handling is the process of writing code to respond to events. In Java, event handling is accomplished through the use of event listeners. An event listener is an object that listens for events & takes appropriate action when an event occurs.

To handle events in Java, you need to follow these steps:

  1. Identify the event source: Determine which component or object will generate the event.
     
  2. Create an event listener: Write a class that implements the appropriate listener interface for the event you want to handle. The listener interface defines the methods that will be called when the event occurs.
     
  3. Register the event listener: Attach the event listener to the event source using the appropriate method. For example, to handle a button click event, you would call the addActionListener() method on the button object & pass an instance of your listener class.
     
  4. Implement the event handling logic: Inside the listener methods, write the code that will be executed when the event occurs. This code can perform any necessary actions, such as updating the GUI, changing the program state, or triggering other events.

Example

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class EventExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Event Example");
        JButton button = new JButton("Click Me!");        
        // Create an event listener
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button clicked!");
            }
        };       
        // Register the event listener
        button.addActionListener(listener);        
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }
}


In this example, we create a simple GUI with a button. We define an ActionListener that prints a message when the button is clicked. The listener is then registered with the button using the addActionListener() method. When the button is clicked, the actionPerformed() method of the listener is called, & the message is printed to the console.

Event Classes in Java

Java provides several built-in event classes that represent different types of events. These classes are part of the java.awt.event & javax.swing.event packages. Each event class contains information about the event that occurred, such as the source of the event, the time it occurred, & any relevant data associated with the event. Some commonly used event classes in Java:

Event ClassDescription
ActionEventRepresents an event that occurs when an action is performed, such as a button click or menu item selection.
MouseEventRepresents an event that occurs when a mouse button is pressed, released, clicked, or moved.
 
KeyEventRepresents an event that occurs when a key on the keyboard is pressed, released, or typed.
ItemEventRepresents an event that occurs when an item in a list, choice, or checkbox is selected or deselected.
WindowEventRepresents an event that occurs when a window is opened, closed, iconified, deiconified, activated, or deactivated.
ComponentEventRepresents an event that occurs when a component is hidden, shown, moved, resized, or painted.


Each event class has its own set of methods that provide access to the event's properties. For example, the ActionEvent class has the getActionCommand() method that returns the command string associated with the event, while the MouseEvent class has the getX() & getY() methods that return the coordinates of the mouse pointer when the event occurred.

When handling events, you'll typically use the appropriate event class to access the relevant information about the event. For example, in an action listener for a button, you might use the getSource() method of the ActionEvent class to determine which button was clicked.

Flow of Event Handling

The flow of event handling in Java follows a specific sequence of steps. Let’s see how an event handling flow:

  1. Event Source: An event begins at the source, which is typically a GUI component or an object that generates the event. For example, a button click event starts when the user clicks a button.
     
  2. Event Object Creation: When an event occurs, an event object is created by the Java runtime environment. The event object contains information about the event, such as the source component, timestamp, & any relevant data.
     
  3. Listener Registration: To handle the event, you need to register an event listener with the event source. This is done by calling the appropriate registration method on the source component & passing an instance of the listener class. For example, to register an action listener for a button, you would call the addActionListener() method on the button object.
     
  4. Event Dispatch: Once the event object is created, it is dispatched to the registered listeners by the Java runtime environment. The event is passed to the appropriate listener method based on the type of event & the listener interface.
     
  5. Listener Method Invocation: The registered listener method is invoked by the Java runtime environment, & the event object is passed as a parameter to the method. The listener method contains the code that defines how to handle the event.
     
  6. Event Handling Logic: Inside the listener method, you write the code that specifies what actions should be taken in response to the event. This can include updating the GUI, changing the program state, triggering other events, or performing any other necessary tasks.
     
  7. Event Consumption: After the event handling logic is executed, the event is considered consumed. If there are no more listeners registered for that event, the event handling process ends.
     
  8. Program Continuation: Once the event is consumed, the program continues its normal execution flow until the next event occurs, & the process repeats from step 1.


Let’s see an example that shows the flow of event handling:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class EventFlowExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Event Flow Example");
        JButton button = new JButton("Click Me!");
        // Listener Registration
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Event Handling Logic
                System.out.println("Button clicked!");
            }
        });
        frame.add(button);
        frame.pack();
        frame.setVisible(true);
    }
}


In this example, the button is the event source. When the button is clicked, an ActionEvent object is created & dispatched to the registered ActionListener. The actionPerformed() method is invoked, & the event handling logic (printing a message) is executed. Finally, the event is consumed, & the program continues running.

Code-Approaches

There are several approaches to handling events in Java. Each approach has its own advantages & use cases. Let's discuss three common approaches to event handling in Java:

Event Handling Within Class

In this approach, the event handling code is written within the same class that contains the event source. The class implements the appropriate listener interface & provides the implementation for the corresponding event-handling method.

Example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class WithinClassExample extends JFrame implements ActionListener {
    private JButton button;
    public WithinClassExample() {
        button = new JButton("Click Me!");
        button.addActionListener(this);
        add(button);
        pack();
        setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
    public static void main(String[] args) {
        new WithinClassExample();
    }
}


In this example, the WithinClassExample class extends JFrame & implements the ActionListener interface. The actionPerformed() method is implemented within the class to handle the button click event.

Event Handling by Other Class

In this approach, the event handling code is written in a separate class from the event source. The separate class implements the appropriate listener interface & provides the implementation for the event handling method. An instance of this class is then registered as a listener on the event source.

Example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class OtherClassExample extends JFrame {
    private JButton button;
    public OtherClassExample() {
        button = new JButton("Click Me!");
        button.addActionListener(new ButtonListener());
        add(button);
        pack();
        setVisible(true);
    }
    public static void main(String[] args) {
        new OtherClassExample();
    }
}
class ButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
}


In this example, the ButtonListener class implements the ActionListener interface & provides the implementation for the actionPerformed() method. An instance of ButtonListener is created & registered as a listener on the button in the OtherClassExample class.

Event Handling by Anonymous Class

In this approach, the event handling code is written using an anonymous inner class. An anonymous class is a local class without a name that is defined & instantiated in a single statement. It allows you to create a one-time implementation of a listener interface without the need for a separate class.

Example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class AnonymousClassExample extends JFrame {
    private JButton button;
    public AnonymousClassExample() {
        button = new JButton("Click Me!");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button clicked!");
            }
        });
        add(button);
        pack();
        setVisible(true);
    }
    public static void main(String[] args) {
        new AnonymousClassExample();
    }
}


In this example, an anonymous class is defined & instantiated inline as an argument to the addActionListener() method. The actionPerformed() method is implemented within the anonymous class to handle the button click event.

Frequently Asked Questions

What is the purpose of event handling in Java?

Event handling in Java allows programs to respond to user actions or system occurrences, enabling interactive & dynamic behavior in applications.

What are the common event classes in Java?

Common event classes in Java include ActionEvent, MouseEvent, KeyEvent, ItemEvent, WindowEvent, & ComponentEvent, each representing different types of events.

What are the different approaches to handle events in Java?

The three main approaches to handle events in Java are: event handling within the same class, event handling by a separate class, & event handling using anonymous classes.

Conclusion

In this article, we have learned about event handling in Java. We discussed the basics of events, their classification into foreground & background events, & the process of event handling using event listeners. We also explained the different event classes provided by Java & their purposes. Additionally, we discussed three common approaches to handle events in Java: within the same class, by a separate class, & using anonymous classes. 

You can also practice coding questions commonly asked in interviews on Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass