For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Event handling in Java is the process that manages an event and executes the necessary action if it takes place. The Event handler refers to the code or collection of instructions used to carry it out.
It is made up of two primary elements:
The source is the entity where the event takes place, and the event listener is tasked with executing suitable actions when an event happens. These Listeners need to be registered with the source object so that the listener can get event notifications.
Event-driven programming holds significance as it allows developers to design responsive, scalable, and modular applications by concentrating on responding to events instead of running code sequentially, resulting in enhanced user experiences and effective resource management. Typical applications encompass UI interactions, real-time data handling, and asynchronous communication.
Boost your Java programming expertise with our Software Development courses and elevate your learning journey!
This guide will concentrate on the intriguing idea of Event Handling in Java. We explore the details of creating interactive applications through event-handling Java examples, covering everything from grasping the idea of events to registering event sources and listeners. Through event handling, you tap into the ability to develop dynamic and interactive software experiences.
Also Read: Event Handling in Java: What is that and How Does it Work?
Event handling in Java pertains to the systems that allow for the development of interactive applications by reacting to events created by users, including keystrokes, mouse movements, and various other actions. Java utilizes a strong event-handling framework centered on the idea of event listeners and event sources.
Components
Events:
Event Sources:
Event Listeners:
Delegation Event Model:
In Java's Event Delegation Model, a source (such as a button) creates an event (for example, a click), and rather than managing it directly, it assigns the event to one or more registered listeners (such as an ActionListener) that then handle the event.
Event listeners and event classes are essential for creating interactive applications, enabling programs to respond to user actions or system events, thereby enhancing user experience and app functionality. Event listeners monitor designated events and initiate code execution upon their occurrence, whereas event classes specify the framework and information linked to those events.
Here is a more comprehensive clarification:
Event Listeners:
Event listeners are systems that enable a program to react to occurrences, like user clicks, key presses, or data modifications.
They "monitor" for certain occurrences and, upon their happening, run a predetermined code segment (an event handler).
Typical events consist of onclick, onmouseover, onload, onfocus, and onblur.
In languages such as JavaScript, event listeners are commonly created using the addEventListener() function.
Event Classes:
Event classes specify the organization and kind of data linked to events.
They serve as templates for generating event objects, which hold details about the event that took place, including the event type, the event source, and any associated information.
Employing event categories aids in the organization and management of event data, simplifying the process of handling events in a systematic manner.
Event classes are generally characterized as classes in programming languages, containing attributes that store the data associated with the event.
Procedures in Managing Events:
Below is a table that outlines several important event classes and listener interfaces in Java:
Event Class | Listener Interface | Description |
ActionEvent | ActionListener | A situation that signifies that an action defined by a component took place, such as pressing a button or choosing an item from the menu list. |
AdjustmentEvent | AdjustmentListener | The adjustment event is triggered by an Adjustable object, such as a Scrollbar. |
ComponentEvent | ComponentListener | An event that signifies a component has shifted, altered in size, or modified its visibility. |
ContainerEvent | ContainerListener | When a component is included in a container or taken out of it, this event is triggered by a container object. |
MouseEvent | MouseListener & MouseMotionListener | The events that take place are a result of the user's interaction with the mouse (Pointing Device). |
KeyEvent | KeyListener | An event that arises from a series of key presses on the keyboard. |
ItemEvent | ItemListener | An event that shows whether an item was chosen or not. |
FocusEvent | FocusListener | These are events related to focus, which encompass focus, focusin, focusout, and blur. |
WindowEvent | WindowListener | An event that shows if a window's status has changed or remains the same |
TextEvent | TextListener | An event that takes place when the text of an object alters. |
MouseWheelEvent | MouseWheelEvent | An event that indicates the mouse wheel has been turned within a component. |
Java provides multiple ways to implement event handling, allowing developers to manage user interactions efficiently. These methods include using event listener interfaces, anonymous inner classes, and lambda expressions. The following sections explore each approach with examples.
In Java, event handling can be accomplished by implementing event listeners. A method to execute event handling is through the use of anonymous classes. An anonymous class enables you to create and initiate an event listener in one expression, resulting in more streamlined code.
Here is an illustration of how you can utilize event handling through an anonymous class in Java:
Code: (Button Click Event Handling Using an Anonymous Class)
import javax.swing.*;
import java.awt.event.*;
public class AnonymousClassExample {
public static void main(String[] args) {
// Create a frame (window)
JFrame frame = new JFrame("Anonymous Class Event Handling Example");
// Create a button
JButton button = new JButton("Click Me!");
// Add event handling using an anonymous class
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Action to be performed when the button is clicked
JOptionPane.showMessageDialog(frame, "Button was clicked!");
}
});
// Set up the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
button.setBounds(100, 70, 100, 30); // Position and size of the button
frame.add(button);
frame.setVisible(true);
}
}
Explanation:
Also Read: Method Reference in Java 8: Explained With Examples
Starting with Java 8 and beyond, event handling can be implemented using lambda expressions. Lambda expressions offer a clearer and more succinct method for managing events in comparison to anonymous classes. They streamline the code by minimizing boilerplate code, resulting in cleaner event handling.
Code: (Button Click Event Handling Using Lambda Expressions)
import javax.swing.*;
import java.awt.event.*;
public class LambdaEventHandlingExample {
public static void main(String[] args) {
// Create a frame (window)
JFrame frame = new JFrame("Lambda Event Handling Example");
// Create a button
JButton button = new JButton("Click Me!");
// Add event handling using a lambda expression
button.addActionListener(e -> {
// Action to be performed when the button is clicked
JOptionPane.showMessageDialog(frame, "Button was clicked!");
});
// Set up the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
button.setBounds(100, 70, 100, 30); // Position and size of the button
frame.add(button);
frame.setVisible(true);
}
}
Explanation:
In Java, you can manage events by creating a distinct class to implement the event listener interface. This method is more organized and is commonly employed when the event-handling logic is more complicated or when there is a desire to distinguish the logic from the user interface (UI) elements.
Here’s an illustration of how to carry out event handling by using a distinct class for the listener implementation:
Code: (Button Click Event Handling Using a Separate Class)
import javax.swing.*;
import java.awt.event.*;
// Class that implements the ActionListener interface
class ButtonClickListener implements ActionListener {
private JFrame frame;
// Constructor to accept the frame
public ButtonClickListener(JFrame frame) {
this.frame = frame;
}
@Override
public void actionPerformed(ActionEvent e) {
// Action to be performed when the button is clicked
JOptionPane.showMessageDialog(frame, "Button was clicked!");
}
}
public class SeparateClassEventHandlingExample {
public static void main(String[] args) {
// Create a frame (window)
JFrame frame = new JFrame("Separate Class Event Handling Example");
// Create a button
JButton button = new JButton("Click Me!");
// Create an instance of the listener class and pass the frame
ButtonClickListener listener = new ButtonClickListener(frame);
// Add the listener to the button
button.addActionListener(listener);
// Set up the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLayout(null);
button.setBounds(100, 70, 100, 30); // Position and size of the button
frame.add(button);
frame.setVisible(true);
}
}
Explanation:
ButtonClickListener:
Distinct Class Event Handling:
Also Read: Adapter Class in Java: Practical Guide with Examples
Handling events in Java is an essential part of creating interactive applications, especially for graphical user interfaces (GUIs). Below are several frequent errors and recommended practices to adhere to while dealing with Event Handling in Java:
Common Mistakes
Not removing event listeners when they are unnecessary can result in memory leaks. For instance, if you add a listener but fail to take it out, it may maintain references to objects that are meant to be garbage collected.
Attaching several event listeners for the same event to a single component may lead to duplicated code execution, unforeseen behavior, and performance concerns.
Excessive use of anonymous inner classes for event listeners can result in code that is difficult to understand and maintain. It can also complicate debugging because the class name isn't clearly specified.
Incorporating complex logic or numerous actions within event-handling methods can render the code more difficult to read and maintain. It may also affect performance.
In multi-threaded settings, events may start occurring while other events are still being handled, leading to concurrency problems.
Updating UI components directly from background threads or listeners (outside the Event Dispatch Thread) can lead to race conditions or exceptions.
At times, event listeners are attached to components, but the listener code mistakenly assumes the incorrect event source, leading to problems or logical errors.
Best Practices
Adopt the Model-View-Controller (MVC) design pattern, wherein the UI elements (View) merely inform the controller of actions, and the controller adjusts the model and refreshes the view as needed. This division renders the code more modular, simpler to test, and easier to maintain.
To create cleaner and more understandable code, utilize lambda expressions for event handling. They offer a brief method to specify event listeners.
Ensure your audience concentrates exclusively on managing the event (such as button clicks or mouse movements) and assign UI updates or business logic to distinct methods or classes. This minimizes unnecessary elements in event-handling methods.
Cluster similar event types or listeners together. For instance, if several buttons exhibit comparable behavior, think about establishing one listener class that manages actions for all, rather than developing individual listeners for each button.
Make sure that event handlers operate quickly and do not block execution. All lengthy tasks (such as database queries or file I/O) must be executed in a different thread to prevent blocking the EDT and freezing the UI. Utilize ActionEvent for common user actions.
For basic UI elements such as buttons or menu options, opt for ActionEvent rather than using other, more specific event types. It is easier and more uniform across elements.
Make remarks on event-handling code, particularly when dealing with intricate logic or when employing a more sophisticated method. This will assist anyone (including you) in comprehending the sequence of events more clearly.
Consistently evaluate your event handlers in detail. Given that event-driven applications are highly interactive, it's crucial to make sure that all potential user actions are included in testing (e.g., clicks, keyboard inputs, mouse movements).
Also Read: Java MVC Project [Step-By-Step Process Explained]
What does this keyword mean in event handling, and how is it deployed?
In an event handler, this pertains to the element that initiated the event, meaning the event target. Nevertheless, its value may vary based on how the event handler is invoked (e.g., arrow functions or when utilizing call, bind, or apply).
What methods can you use to manage events in a React application?
In React, handling events is performed with synthetic events (which serve as wrappers for the native events of the browser). You create event handlers as functions (for instance, handleClick) and link them to elements through JSX properties (like <button onClick={handleClick}>Click Me</button>).
What various kinds of events exist in JavaScript?
Typical categories of events in JavaScript consist of:
What distinguishes preventDefault() from stopPropagation()?
preventDefault() stops the usual action of an event from taking place (e.g., halting a form submission).
stopPropagation() prevents the event from moving through the DOM hierarchy (halts bubbling or capturing).
What are some effective techniques for managing events in JavaScript?
Also Read: Top 32 Exception Handling Interview Questions and Answers in 2025 [For Freshers & Experienced]
Exercise 1: Create a Java Program to Handle Keyboard Events
Here’s an easy Java program to manage keyboard events utilizing the KeyListener interface. The KeyListener interface in Java captures keyboard events and includes three methods: keyPressed(), keyReleased(), and keyTyped().
Java Program to Handle Keyboard Events
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class KeyboardEventExample extends JFrame implements KeyListener {
private JTextArea textArea;
public KeyboardEventExample() {
// Set up the JFrame
setTitle("Keyboard Event Handler");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JTextArea to display typed characters
textArea = new JTextArea();
textArea.addKeyListener(this); // Add the KeyListener to the text area
add(textArea);
setVisible(true);
}
// Method to handle keyPressed event
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
// Method to handle keyReleased event
@Override
public void keyReleased(KeyEvent e) {
System.out.println("Key Released: " + e.getKeyChar());
}
// Method to handle keyTyped event
@Override
public void keyTyped(KeyEvent e) {
System.out.println("Key Typed: " + e.getKeyChar());
}
public static void main(String[] args) {
// Create an instance of the KeyboardEventExample class
new KeyboardEventExample();
}
}
How It Works:
KeyListener Interface:
JFrame:
keyPressed():
keyReleased():
keyTyped():
Output:
When you type in the JTextArea, the console will display:
Key Pressed: A
Key Released: A
Key Typed: A
This is a straightforward calculator created in Java that utilizes event handling through the ActionListener interface. This calculator will carry out fundamental operations such as addition, subtraction, multiplication, and division.
Java Program: Simple Calculator with Event Handling
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame implements ActionListener {
// Create necessary components (buttons, text field, etc.)
private JTextField display;
private JButton[] numberButtons;
private JButton addButton, subtractButton, multiplyButton, divideButton, equalsButton, clearButton;
private String operator;
private double firstNum, secondNum, result;
public SimpleCalculator() {
// Set up the frame
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Initialize components
display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 24));
add(display, BorderLayout.NORTH);
// Create the panel for buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
add(panel, BorderLayout.CENTER);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
panel.add(numberButtons[i]);
}
// Initialize operator buttons
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
equalsButton = new JButton("=");
clearButton = new JButton("C");
// Add action listeners to operator buttons
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
equalsButton.addActionListener(this);
clearButton.addActionListener(this);
// Add operator buttons to the panel
panel.add(addButton);
panel.add(subtractButton);
panel.add(multiplyButton);
panel.add(divideButton);
panel.add(equalsButton);
panel.add(clearButton);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ((command.charAt(0) >= '0' && command.charAt(0) <= '9')) {
// If a number button is clicked, append the number to the display
display.setText(display.getText() + command);
} else if (command.equals("C")) {
// If 'C' (clear) is clicked, clear the display
display.setText("");
} else if (command.equals("=")) {
// If '=' is clicked, perform the calculation
secondNum = Double.parseDouble(display.getText());
switch (operator) {
case "+":
result = firstNum + secondNum;
break;
case "-":
result = firstNum - secondNum;
break;
case "*":
result = firstNum * secondNum;
break;
case "/":
result = firstNum / secondNum;
break;
}
display.setText(String.valueOf(result));
} else {
// If an operator button is clicked, store the operator and the first number
if (!display.getText().isEmpty()) {
firstNum = Double.parseDouble(display.getText());
operator = command;
display.setText("");
}
}
}
public static void main(String[] args) {
// Create and display the calculator
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
}
}
How the Program Works:
JTextField (display): This is the text box that displays the numbers and outcomes. It’s not editable (read-only).
JButtons: Every digit (0-9) and operation button (+, -, *, /, =, C) is symbolized by a JButton.
Event Handling: The actionPerformed() function is activated each time a button is clicked. Depending on the button that was activated:
When a number button is pressed, its value is added to the display.
If an operator (+, -, *, /) is selected, the number currently shown is recorded, and the operator gets saved.
When the equals (=) button is pressed, the program carries out the calculation according to the operator and shows the outcome.
When the clear (C) button is pressed, the screen is reset.
Arrangement: A GridLayout organizes the buttons (4 rows and 4 columns), while a BorderLayout is utilized to structure the whole window.
How to Operate:
Characteristics:
It carries out fundamental mathematical calculations (+, -, *, /).
The C button can be used to clear the display.
It shows results once the = button is pressed.
Output:
Clicking the buttons: 2, +, 3, =, will result in the display showing 5.0.
This is a straightforward calculator app showcasing fundamental event management in Java. You can enhance it by incorporating more intricate operations or upgrading its user interface.
This is a straightforward Java GUI application that alters the window's background color depending on the button presses. We will utilize JFrame, JButton, and ActionListener to achieve this feature.
Java Program: Change Background Color on Button Click
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BackgroundColorChanger extends JFrame implements ActionListener {
// Create buttons for each color change
private JButton redButton, greenButton, blueButton, yellowButton, resetButton;
public BackgroundColorChanger() {
// Set up the frame
setTitle("Background Color Changer");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Initialize buttons
redButton = new JButton("Red");
greenButton = new JButton("Green");
blueButton = new JButton("Blue");
yellowButton = new JButton("Yellow");
resetButton = new JButton("Reset");
// Add action listeners to buttons
redButton.addActionListener(this);
greenButton.addActionListener(this);
blueButton.addActionListener(this);
yellowButton.addActionListener(this);
resetButton.addActionListener(this);
// Add buttons to the frame
add(redButton);
add(greenButton);
add(blueButton);
add(yellowButton);
add(resetButton);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
// Change the background color based on the button clicked
if (command.equals("Red")) {
getContentPane().setBackground(Color.RED);
} else if (command.equals("Green")) {
getContentPane().setBackground(Color.GREEN);
} else if (command.equals("Blue")) {
getContentPane().setBackground(Color.BLUE);
} else if (command.equals("Yellow")) {
getContentPane().setBackground(Color.YELLOW);
} else if (command.equals("Reset")) {
getContentPane().setBackground(null); // Reset to default background
}
}
public static void main(String[] args) {
// Create and display the GUI
BackgroundColorChanger frame = new BackgroundColorChanger();
frame.setVisible(true);
}
}
How It Works:
How to Operate:
Characteristics:
The application includes five buttons: one for each hue (Red, Green, Blue, Yellow), along with a Reset button to revert to the original background color.
Upon clicking a button, the window's background color alters to match the designated hue.
The Reset button returns the background color to its default setting.
Output:
Pressing the "Red" button will modify the background color to red.
Pressing the "Reset" button will restore the background to its original condition.
This is a straightforward illustration of a GUI application that reacts to user actions through event management. You can enhance this by including additional colors or personalizing the interface further!
If you want to enhance your grasp of Event Handling in Java and acquire practical experience, I strongly recommend checking out upGrad’s courses! upGrad presents a range of online programs and courses in Java development aimed at delivering both theoretical insights and hands-on experience.
By joining an upGrad course, you'll not only grasp essential concepts such as Event Handling but also have the chance to engage in projects, real-world case analyses, and interactive tasks that will aid you in mastering Java programming. Whether you're beginning your journey or seeking to enhance your abilities, these courses are designed to support you at each stage of your educational path.
The main advantages of upGrad’s Java-centric programs consist of:
Discover additional information about their Java and related courses on upGrad's official site!
Here are some Java and related courses on upGrad's official site:
Reach out to an upGrad centre near you to fast-track your education and career. Seize this chance to gain proficiency in a highly sought-after programming language!
Similar Reads:
Event classes in Java specify particular events, which include button clicks or mouse moves, and listener interfaces establish the procedures through which objects can respond to such events.
Java utilizes the ActionListener interface to provide classes with notification alerts whenever users trigger an action event, such as button clicks or menu selections, so they can implement the necessary actionPerformed method for event handling.
When using KeyListener you need to fulfill implementation requirements for all methods (keyPressed, keyReleased, keyTyped) without needing complete utilization of each one.
KeyAdapter supplies default empty method implementations for the entire interface yet requires you to override only specific targeted methods.
Inner classes within event handling form part of the overall system.
Event-handling logic becomes more organized when developers use inner classes (also known as nested classes) to define code blocks within the generating component, since this places event logic close to its origin.
ActionListener provides a mechanism to address action events in the user interface, such as button clicks and form submissions. MouseListener enables programmers to manage events that arise from mouse interactions with components as well as mouse click activities.
You have the ability to develop custom events within the Java programming language. Java enables users to build their own event types that come in handy when the requirement involves managing unique application events or user-triggered specific actions.
The prevention of memory leaks during event handling requires proper management of event handlers through detachment and constant observation of circular DOM references.
A debugger serves as the basic debugging instrument within Java applications. Integrated development environments such as IntelliJ IDEA, Eclipse, and NetBeans offer contemporary debugging capabilities for programmers to implement breakpoints and view variable values as well as execute program code unit by unit.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.