Advanced Java Programming - Old Questions
2. why do we need event handling? Discuss the process of handling events with example. Differentiate event listener interface with adapter class. (3+4+3)
Answer
AI is thinking...
Change in the state of an object is known as event. Events are generated as result of user interaction with the graphical user interface components. For example, click on button, dragging mouse, entering a character through keyboard, selecting an item from list etc.
Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Event handling has three main components,
- Events : An event is a change of state of an object.
- Events Source : Event source is an object that generates an event.
- Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.
A source generates an Event and send it to one or more listeners. Listener waits until it receives an event. Once the event is received, the listener process the event and then returns. Listener needs to be registered with the source object so that the listener can receive the event notification. There are three things that are done in event handling:
1. Create a class that represents the event handler.
2. Implement an appropriate interface called “event listener interface” in the above class.
3. Register the event handler
The event listeners listen for a particular event and whenever the event occurs they fire the action that is registered for them.
Example
import java.awt.event.*;
import javax.swing.*;
public class EventListener extends JFrame implements
ActionListener {
public
EventListener(){
JButton btn =
new JButton("Click Me");
add(btn);
btn.addActionListener(this);
//registering the event handler
setSize(100,
100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"Hello");
}
public static void main(String []a) {
new
EventListener();
}
}
Here, whenever the “Click Me” button is clicked, an event is generated and a particular action of opening a dialog box and displaying message “Hello” happens.
Event Listener Interface vs Adapter Class
Many of the listener interfaces have more than one method. When
we implement a listener interface in any class then we must have to implement
all the methods declared in that interface because all the methods in an
interface are final and must be override in class which implement it.
Adapter class makes it easy to deal with
this situation. An adapter class provides empty implementations of all methods
defined by that interface. Adapter classes are very useful if we want to
override only some of the methods defined by that interface.