For working professionals
For fresh graduates
More
Step by Step Java Tutorial Con…
1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
Now Reading
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
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.
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
+918045604032
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.