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

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

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

1. 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.

2. 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 the events are listed in the java.awt.event package.

3. 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.

4. Event Listeners

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

How to perform event handling

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:

import java.awt.event.*;
import java.awt.*;
class EventActEx1 extends Frame implements ActionListener
 
{
   
TextField txtfld;
   
EventActEx1()
      {
       
txtfld= new TextField();
       
txtfld.setBounds(65,60,190,20);
       
Button bt=new Button("Click me");
       
bt.setBounds(100,120,80,30);
       
bt.addActionListener(this);
       
add(bt);add(txtfld);
       
setSize(350,350);
       
setLayout(null);
       
setVisible(true);
      }
   
public void actionPerformed(ActionEvent e)
     
{
       
txtfld.setText("welcome 2 c-sharpcorner.com");
      }
   
public static void main(String args[])
     
{
       
new EventActEx1();
     
}
  }

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.

import java.awt.*;
import java.awt.event.*;
public class EventAction extends Frame implements ActionListener
 
{
    Label l
;
    public static void main(String argv[]
)
     
{
        EventAction t = new EventAction
();
     
}
    public EventAction
()
     
{
        super("Event generate in java"
);
        setLayout(new BorderLayout
());
       
try
         
{
            Button b = new Button("Enter your name in this block"
);
            b.addActionListener(this
);
            add(b, BorderLayout.NORTH
);
            Button b1 = new Button("Write something about your self"
);
            b1.addActionListener(this
);
            add(b1, BorderLayout.SOUTH
);
            l = new Label("c-sharpcorner.com"
);
            add(l, BorderLayout.CENTER
);
            addWindowListener(new WindowAdapter
()
             
{
                public void windowClosing(WindowEvent we
)
                 
{
                    System.exit(0
);
                  
}
              
});
           
}
          catch (Exception e
)
           
{}
           setSize(300,300
);
           setVisible(true
);
        
}
     
public void actionPerformed(ActionEvent e)
      
{
              Button bton = (Button)e.getSource
();
              String strng = bton.getLabel
();
              l.setText(strng
);
      
}

}

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

Up Next
    Ebook Download
    View all
    Learn
    View all