Types of events in Java
An event is one of the most important concepts in Java. The change in the state of an object or behavior by performing actions is referred to as an Event in Java. Actions include button click, keypress, page scrolling, or cursor movement.
Java provides a package java.awt.event that contains several event classes.
We can classify the events in the following two categories:
Foreground events are those events that require user interaction to generate. In order to generate these foreground events, the user interacts with components in GUI. When a user clicks on a button, moves the cursor, and scrolls the scrollbar, an event will be fired.
Background events don't require any user interaction. These events automatically generate in the background. OS failure, OS interrupts, operation completion, etc., are examples of background events.
Delegation Event Model
A mechanism for controlling the events and deciding what should happen after an event occur is referred to as event handling. Java follows the Delegation Event Model for handling the events.
The Delegation Event Model consists of Source and Listener.
Buttons, checkboxes, list, menu-item, choice, scrollbar, etc., are the sources from which events are generated.
The events which are generated from the source are handled by the listeners. Each and every listener represents interfaces that are responsible for handling events.
To learn more about Delegation Event Model, go through the following link:
We need to register the source with the listener for handling events. Different types of classes provide different registration methods.
The syntax of registering the source with the listener is as follows:
For example, if we need to register Key and Action events, we use the addActionListener() and addKeyListener() methods.
These are some of the most used Event classes:
Let's take an example to understand how we can work with the events and listeners: