Introduction To Event Handling In Java

Introduction

 
In this article, we discuss event handling (event and listener) in Java.
 

Event

 
An event happens when something changes within a graphical user interface.
 
We can say that events are objects in Java.  It comes under some classes stored in java.util.EvenObject.
 
For example, events occur when a user clicks on a button, clicks on a combo box, or types characters into a text field, etcetera, such as in the following:
  • For a button, the event that is fired is the ActionListener.
  • For a text field, it's the KeyEvent.
The following figure clarifies events.  When we click on the "click me" button an event is generated; that change event generates another frame that shows our message, that is passed to the program.
 
event.png
 

Listener class in Java

 
This class listens for the events in the application.  It controls the application, without affecting its internal mechanism.
 
The Listener interfaces check the continuity of the work.  The dispatching of a class must be able to rely on each of its listeners to contain the method that is executed, when the event occurs.  It can be easily done in Java, by the use of an Interface class.  The important point is that a class, which is going to be a listener, must implement that interface. They are:
  1. ServletContextListener and
  2. HttpSessionListener.
When a listener is created, by the property of the interface ",all the methods of that interface must be implemented".  Some listeners, like the ActionListener, have only one method.
 

Event Handling in Java

 
The Abstract Window Toolkit (AWT) uses event driven programming to do processing of user actions, one that underlies all modern window systems programming.  Within the AWT, all user actions belong to an abstract set of things called events.  An event describes, in sufficient detail, a particular user action . Rather than, the program actively collecting user-generated events.  The Java run time notifies the program when an interesting event occurs.  Programs that handle user interaction in this fashion, are said to be event driven.
 
Event Handling
 
Event Handling provides four types of classes; they are:
  1. Event Adapters
  2. Event classes
  3. Event Sources
  4. Event Listeners

Event Adapters

 
In a program, when a listener has many abstract methods to override, it becomes complex for the programmer to override all of them.
For example, for closing a frame, we must override seven abstract methods of WindowListener, but we need only one method of them.
For reducing complexity, Java provides a class known as "adapters" or adapter class.  Adapters are abstract classes, that are already being overriden.
 

Event classes

 
Every event source generates an event and is named by a Java class.  An event is generated when something changes within a graphical user interface.
 
For example, the event generated by a:
  • Button is known as an ActionEvent
  • Checkbox is known as an ItemEvent
All of the events are listed in the java.awt.event package.
 

Event Sources

 
Event Sources are responsible for generating events and are called components.
 
The source for an event can be a button, TextField or a Frame etcetera.
 ,

Event Listeners

 
Events are handled by a special group of interfaces, known as "listeners".
 

How to perform event handling in Java

 
The following is required to perform event handling:
  1. Implement the Listener interface and override its methods
  2. Register the component with the listener
For adding various components, we use publics methods, for example:
  • Button
       
    void addActionListener( ActionListener a)
  • List
       
    void addActionListener(ActionListener a)
        void addItemListener(ItemListener a)
  • Choice
       
    void addItemListener(ItemListener x)
  • MenuItem
       
    void addActionListener(ActionListener x)
  • TextField
       
    void addActiontListener(ActionListener x)
        void addTextListener(TextListener x)
  • TextArea
       
    void addTextListener(TextListener x)
  • Checkbox
       
    void addItemListener(ItemListener x)
We can use event handling in:
  • the same class
  • another class
  • anonymously

Event Handling within same class

 
The following is a sample of event handling, within the same class:
  1. import java.awt.event.*;  
  2. import java.awt.*;  
  3. class EventActEx1 extends Frame implements ActionListener {  
  4.     TextField txtfld;  
  5.     EventActEx1() {  
  6.         txtfld = new TextField();  
  7.         txtfld.setBounds(656019020);  
  8.         Button bt = new Button("Click me");  
  9.         bt.setBounds(1001208030);  
  10.         bt.addActionListener(this);  
  11.         add(bt);  
  12.         add(txtfld);  
  13.         setSize(350350);  
  14.         setLayout(null);  
  15.         setVisible(true);  
  16.     }  
  17.     public void actionPerformed(ActionEvent e) {  
  18.         txtfld.setText("welcome 2 c-sharpcorner.com");  
  19.     }  
  20.     public static void main(String args[]) {  
  21.         new EventActEx1();  
  22.     }  
  23. }  
Output
 
fig-1.jpg
 
When we click on "click me" button, an event is generated that shows the "welcome 2 c-sharpcorner.com" message in the textfield area.  Hence, we see an event change in this program.
 
fig-2.jpg
 
Event Handling Example
 
The following is a sample of creating a frame that contains two buttons and one text field.
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class EventAction extends Frame implements ActionListener {  
  4.     Label l;  
  5.     public static void main(String argv[]) {  
  6.         EventAction t = new EventAction();  
  7.     }  
  8.     public EventAction() {  
  9.         super("Event generate in java");  
  10.         setLayout(new BorderLayout());  
  11.         try {  
  12.             Button b = new Button("Enter your name in this block");  
  13.             b.addActionListener(this);  
  14.             add(b, BorderLayout.NORTH);  
  15.             Button b1 = new Button("Write something about your self");  
  16.             b1.addActionListener(this);  
  17.             add(b1, BorderLayout.SOUTH);  
  18.             l = new Label("c-sharpcorner.com");  
  19.             add(l, BorderLayout.CENTER);  
  20.             addWindowListener(new WindowAdapter() {  
  21.                 public void windowClosing(WindowEvent we) {  
  22.                     System.exit(0);  
  23.                 }  
  24.             });  
  25.         } catch (Exception e) {}  
  26.         setSize(300300);  
  27.         setVisible(true);  
  28.     }  
  29.     public void actionPerformed(ActionEvent e) {  
  30.         Button bton = (Button) e.getSource();  
  31.         String strng = bton.getLabel();  
  32.         l.setText(strng);  
  33.     }  
  34. }  
Outputs
 
fig-3.jpg
 
When we click on "Enter your name in this block" button an action is generated that provides a text field to write your name.
 
fig-4.jpg
 
When we click on the "Write something about your self" button, an action is generated that provides an area to write something about yourself.
 
fig-5.jpg


Similar Articles