Event Handling in Java
An event can be defined as changing the state of an object or
behavior by performing actions. Actions can be a button click, cursor
movement, keypress through keyboard or page scrolling, etc.
The [Link] package can be used to provide various event
classes.
Classification of Events
Foreground Events
Background Events
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to
generate, i.e., foreground events are generated due to interaction
by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the scroll
bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are
known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what
should happen after an event occur. To handle the events, Java
follows the Delegation Event model.
Delegation Event model
It has Sources and Listeners.
Delegation Event Model
Source: Events are generated from the source. There are
various sources like buttons, checkboxes, list, menu-item,
choice, scrollbar, text components, windows, etc., to
generate events.
Listeners: Listeners are used for handling the events
generated from the source. Each of these listeners
represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with the
listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to
register.
Event Classes in Java
Event Class Listener Interface Description
An event that indicates that a
component-defined action occurred
ActionEvent ActionListener
like a button click or selecting an
item from the menu-item list.
Event Class Listener Interface Description
The adjustment event is emitted by
AdjustmentEvent AdjustmentListener
an Adjustable object like Scrollbar.
An event that indicates that a
ComponentEvent ComponentListener component moved, the size
changed or changed its visibility.
When a component is added to a
container (or) removed from it, then
ContainerEvent ContainerListener
this event is generated by a
container object.
These are focus-related events,
FocusEvent FocusListener which include focus, focusin,
focusout, and blur.
An event that indicates whether an
ItemEvent ItemListener
item was selected or not.
An event that occurs due to a
KeyEvent KeyListener sequence of keypresses on the
keyboard.
The events that occur due to the
MouseListener &
MouseEvent user interaction with the mouse
MouseMotionListener
(Pointing Device).
An event that specifies that the
MouseWheelEvent MouseWheelListener mouse wheel was rotated in a
component.
An event that occurs when an
TextEvent TextListener
object’s text changes.
An event which indicates whether a
WindowEvent WindowListener window has changed its status or
not.
Note: As Interfaces contains abstract methods which need to
implemented by the registered class to handle events.
Different interfaces consists of different methods which are specified
below.
Listener Interface Methods
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
MouseMotionListene mouseMoved()
r mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
WindowListener windowActivated()
windowDeactivated()
windowOpened()
Listener Interface Methods
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
Flow of Event Handling
1. User Interaction with a component is required to generate
an event.
2. The object of the respective event class is created
automatically after event generation, and it holds all
information of the event source.
3. The newly created object is passed to the methods of the
registered listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing
the event handling code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler
may throw errors due to the unavailability of some packages.
Event Handling Within Class
Java
// Java program to demonstrate the
// event handling within the class
import [Link].*;
import [Link].*;
class GFGTop extends Frame implements
ActionListener {
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of the component
[Link](60, 50, 180, 25);
Button button = new Button("click
Here");
[Link](100, 120, 80, 30);
// Registering component with listener
// this refers to current instance
[Link](this);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
// implementing method of actionListener
public void actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("GFG!");
}
public static void main(String[] args)
{
new GFGTop();
}
}
Output
After Clicking, the text field value is set to GFG!
Explanation
1. Firstly extend the class with the applet and implement the
respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e.
ActionEvent by addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class
Java
// Java program to demonstrate the
// event handling by the other class
import [Link].*;
import [Link].*;
class GFG1 extends Frame {
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click
Here");
[Link](100, 120, 80, 30);
Other other = new Other(this);
// Registering component with listener
// Passing other class as reference
[Link](other);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
public static void main(String[] args)
{
new GFG2();
}
}
Java
/// import necessary packages
import [Link].*;
// implements the listener interface
class Other implements ActionListener {
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
}
public void actionPerformed(ActionEvent e)
{
// setting text from different class
[Link]("Using
Different Classes");
}
}
Output
Handling event from different class
Event Handling By Anonymous Class
Java
// Java program to demonstrate the
// event handling by the anonymous class
import [Link].*;
import [Link].*;
class GFG3 extends Frame {
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click
Here");
[Link](100, 120, 80, 30);
// Registering component with listener
anonymously
[Link](new
ActionListener() {
public void
actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("Anonymous");
}
});
// add Components
add(textField);
add(button);
//make size viewable
setSize(300,300);
// set visibility
setVisible(true);
}
public static void main(String[] args)
{
new GFG3();
}
}
Output