Page 413 - CITS - Computer Software Application -TT
P. 413
COMPUTER SOFTWARE APPLICATION - CITS
Listener - It is also known as event handler. Listener is responsible for generating response to an event. From
java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the
event is received , the listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from the logic that generates
the event. The user interface element is able to delegate the processing of an event to the separate piece of code.
In this model, Listener needs to be registered with the source object so that the listener can receive the event
notification. This is an efficient way of handling the event because the event notifications are sent only to those
listener that want to receive them.
Steps involved in event handling
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically and information about the source and the event
get populated with in same object.
Event object is forwarded to the method of registered listener class.
the method is now get executed and returns.
Points to remember about listener:-
In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast
some public abstract callback methods which must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a
source object.
Callback Methods:-
These are the methods that are provided by API provider and are defined by the application programmer and
invoked by the application developer. Here the callback methods represents an event method. In response to an
event java are will fire callback method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it’s events the source must register itself to the listener.
Event Handling Example:-
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}
private void prepareGUI(){
400
CITS : IT&ITES - Computer Software Application - Lesson 116 - 119