Tutorial Playlist
Event handling in Java can be considered a paradigm in the interface that enables a listener in your applications and triggers responses based on the input received.
So what is an event? An event could be a specific user action, such as pressing a key or clicking the mouse. Now when any of these specified actions take place, a set of pre-determined, pre-programmed actions will set into course. Event handling is used by programmers and developers to make the code more interactive and to optimize and, to a certain degree, even customize user experiences.
To understand the components of event handling in Java, you must focus on three aspects. They are the event source, the event handler, and the event listener. They are tasked with generating, capturing, and executing the set of codes when the event happens, respectively.
This tutorial will focus on the interesting concept of event handling in Java. From understanding the concept of events to registering event sources and listeners, we delve into the intricacies of building interactive applications with event-handling Java examples. With event handling, you harness the power to create dynamic and interactive software experiences.
Event handling in Java can be defined as the process of designing and deploying user-interaction or system-action-sensitive code. It is a mechanism that aims to identify or “listen” for specific events such as a mouse click, button activations, etc. It differs from traditional programming in that event-driven programming is more user-centered, and the outcomes depend on the user's actions rather than a pre-designed sequence of codes.
If you are in a team organizing an event, it is natural that different team members would be “delegated” different event responsibilities. In the same way, the delegation event model is an architecture of event handling in the Java paradigm that allows objects to delegate the responsibility of handling these events to other objects. The object to which the event is delegated is called the “listener object.”
Registering the source with a listener in the Delegation Event Model involves connecting the source object to the listener object. This allows the listener to receive and handle events generated by the source. This enables effective communication and event-driven behavior in Java.
Events are handled through a systematic process in Java. When an event occurs, the event source detects it and notifies the registered event listener. The listener, equipped with the appropriate event handling code, responds accordingly. This structured approach ensures seamless communication and enables applications to react promptly and accurately to user interactions.
import java.util.Scanner;
public class EventHandlingExample {
  public static void main(String[] args) {
    // Create a Scanner object to read user input
    Scanner scanner = new Scanner(System.in);
    // Prompt the user to enter their name
    System.out.print("Enter your name: ");
    String name = scanner.nextLine();
    // Prompt the user to enter their age
    System.out.print("Enter your age: ");
    int age = scanner.nextInt();
    // Register an event handler for the Enter key press event
    scanner.nextLine(); // Consume the remaining newline character
    System.out.println("Press Enter to submit.");
    scanner.nextLine(); // Wait for the Enter key press event
    // Process the submitted data
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    // Close the scanner
    scanner.close();
  }
}
The above example demonstrates a simple form of event handling in Java using the Scanner class. It allows the user to enter their name and age, and then submit the data by pressing the Enter key.
First, the program creates a Scanner object to read user input. The user is prompted to enter their name, and the input is stored in a String variable called name. Then, the user is prompted to enter their age, and the input is stored in an int variable called age.
Next, the program registers an event handler for the Enter key press event. This is done by calling scanner.nextLine() to consume the newline character left after reading the age input. The message "Press Enter to submit." is displayed, and another scanner.nextLine() is used to wait for the Enter key press event.
Once the Enter key is pressed, the program executes and processes the submitted data. It displays the name and age that the user entered using System.out.println(). Finally, the scanner.close() method is called to close the Scanner object and free any associated system resources.
When you run this program, it will prompt you to enter your name and age. After entering the data, you can press Enter to submit it. The program will then display the submitted name and age.
Event handlers are responsible for defining the actions or behaviors that should occur in response to specific events. They contain the implementation code that handles the event and performs the desired tasks. Event handlers are typically implemented as methods within a class. When an event occurs, the associated event handler is invoked to respond to that event.
Event sources are objects that generate events. They are the entities or components that trigger events when specific actions or conditions occur. Examples of event sources include buttons, text fields, mouse clicks, or keyboard inputs. Event sources are responsible for creating and dispatching the corresponding event objects when the specific event occurs.
Event listeners are interfaces or classes that define the methods to handle events. They are responsible for listening to events generated by event sources and invoking the appropriate event handlers to respond to those events. Event listeners implement the methods defined in the listener interface, which contain the logic for handling the events. Event listeners are registered with the event sources to receive and process the events.
ActionEvent: This represents the user's action, such as clicking a button or selecting a menu item.
MouseEvent: Represents mouse-related events, such as mouse clicks, movement, or dragging.
KeyEvent: Represents keyboard-related events, such as key presses or key releases.
WindowEvent: Represents events related to windows or frames, such as window opening, closing, or resizing.
FocusEvent: Represents events related to focus, such as when a component gains or loses focus.
ActionListener: Defines methods to handle ActionEvents.
MouseListener: Defines methods to handle MouseEvent.
MouseMotionListener: Defines methods to handle mouse motion events.
KeyListener: Defines methods to handle KeyEvent.
WindowListener: Defines methods to handle WindowEvent.
FocusListener: Defines methods to handle FocusEvent.
Here are the steps to perform event handling in Java:
The specific registration methods can vary depending on the event source and the event listener interface being used. Some common registration methods include addActionListener(), addMouseListener(), or addKeyListener(). The event source class provides these methods and allow you to register the appropriate event listener for the specific event type.
import java.util.Scanner;
public class EventHandlingWithinClass {
  public static void main(String[] args) {
    EventHandlingWithinClass eventHandling = new EventHandlingWithinClass();
    eventHandling.startListening();
  }
  Â
  public void startListening() {
    Scanner scanner = new Scanner(System.in);
    Â
    System.out.println("Enter a number: ");
    int number = scanner.nextInt();
    Â
    // Event handling logic
    if (number % 2 == 0) {
      System.out.println(number + " is even.");
    } else {
      System.out.println(number + " is odd.");
    }
    Â
    scanner.close();
  }
}
This program prompts the user to enter a number and performs event handling logic to determine if the number is even or odd. The event handling logic is implemented within the same class where the main method resides. The program uses a Scanner object to read user input and performs the necessary calculations based on the input.
import java.util.Scanner;
public class EventHandlingOuterClass {
  public static void main(String[] args) {
    EventHandlingLogic eventHandling = new EventHandlingLogic();
    eventHandling.startListening();
  }
}
class EventHandlingLogic {
  public void startListening() {
    Scanner scanner = new Scanner(System.in);
    Â
    System.out.println("Enter your name: ");
    String name = scanner.nextLine();
    Â
    System.out.println("Hello, " + name + "! Welcome to the event handling program.");
    Â
    scanner.close();
  }
}
This program prompts the user to enter their name and displays a welcome message.
The event handling logic is implemented in a separate outer class called EventHandlingLogic. The main method creates an instance of the EventHandlingLogic class and calls the startListening method to initiate the event handling process. The program uses a Scanner object to read user input and displays the welcome message based on the input.
import java.util.Scanner;
public class EventHandlingAnonymousClass {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    Â
    System.out.println("Enter a string: ");
    String input = scanner.nextLine();
    Â
    // Event handling logic with anonymous class
    Runnable eventHandler = new Runnable() {
      @Override
      public void run() {
        System.out.println("Length of the string: " + input.length());
      }
    };
    Â
    eventHandler.run();
    Â
    scanner.close();
  }
}
This program prompts the user to enter a string and calculates the length of the string.
The event handling logic is implemented using an anonymous class that implements the Runnable interface. The program creates an anonymous class instance and invokes the run method to execute the event handling logic.
The event handling logic accesses the input string and calculates its length, then displays it to the user. The program uses a Scanner object to read user input and performs the necessary calculations based on the input.
Foreground events are user-triggered events that require immediate attention and interaction. These events are associated with user actions such as button clicks, menu selections, mouse movements, or keystrokes. The program actively listens and responds to these events in real time. Examples of foreground events include clicking a button, pressing a key, or selecting an item from a menu.
Background events are system-triggered events that occur without direct user interaction.
These events typically occur in the background without the user's immediate attention. The program may respond to these events periodically or as needed. Examples of background events include timers, network events, file system events, or system notifications.
This tutorial provides a comprehensive look into the concept of event handling in Java. You can build dynamic and interactive applications by understanding how events are captured, registered, and handled. Embrace the power of event handling and unlock endless possibilities to create user-centric software experiences. Happy coding.
1. What is an event listener in Java?
An event listener in Java is the interface that handles a particular event. In Java, there is scope for several event listener classes.
2. What are the two types of event handling?
We can classify the events into two types, namely- foreground events and background events.
3. What is event handling in OOPs?
Event handling is the mechanism of preparing in advance for an event to occur, and then when the opportunity presents itself, the pre-determined set of actions (codes) are triggered off.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...