Event handling in java using Listener and Adapters


Listener and Adapters are two different way to accomplish the event handling in java. all the event sources have different type of class support. There are mouse and key events, window and focus events, srcoll bar and checkboxes event and many more.

Events Handling is a powerful aspect of Java language. It allows you to create the Graphical Applications with easy to do operations. Event handling means, to create a reaction for every action one does with any component on the application screen. There are different event classes but we shall look at them briefly after we define the element of event handling mechanism.

What is Event ?

Event, in deep microprocessor terms is an interrupt signal to the processor, but let us not go deep down in computer hardware and The event is actually an object in Java which represents the state change of the component. This state change could be the clicking of any button, changing size of window, minimizing, maximizing or closing of frame, moving scrollbar or moving mouse, clicking mouse, pressing keyboard and many more. All these actions generate the event object.

What are Event sources?

Event Sources are the components on which the action is performed, for example if we are clicking the button, the source of event would be the button. It will generate a MouseClicked event or ActionEvent. These sources are binded with event listeners, don't worry we are going to describe listeners next. But when a event occurs and event source generates an event it passes it to EventListener to handle.

What are Event Listener?

Event Listener are the Objects that gets notification when any event is created. Java provide different type of listener for different type of objects. Also you must remember to bind the listener with the event source so that listener know if an event is generated.

Java provides support for various event types. All the event classes are decedent from EventObject class and for each type of event class we also have corresponding Listener interface and Adapter class also. Here is how we brief the Event classes we have got.

Action Event: Generated when a button is press, list item is double clicked or a menu is selected.

AdjustmentEvent: Generated when a scroll bar is moved.

ComponentEvent: Generated when a component is set to non-visibility or visibility, moved or resized.

ContainerEvent: Generated when a component is added to or removed from a container.

FocusEvent: Generated when a component receives or loses focus.

InputEvent: It is an abstract class for Input type of events.

ItemEvent: Generated when a check box or list item is clicked also when menu item is selected or deselected.

KeyEvent: Generated when input is received from keyboard.

MouseEvent and MouseWheeelEVent Generated when the mouse action is performed like click, move or wheel scroll etc.

TextEvent: Generated when value of text is changed in text field or area.

WindowEvnet: Generated when a window is active, closed, minimized, restored etc.

Each of these class has its own meaning, they contains the methods and MASKs which helps to work with the event on machine level. There are two well known ways to work with events. Using the EventListener interfaces and using the adapter classes.

Now we will be describing the two ways separately. First let us look at the listeners.


package events;
import java.awt.event.*;
import java.awt.*;
public class ListenersEvent extends Frame implements ActionListener,MouseMotionListener{
    
    Button b;
    
    ListenersEvent(){
        super("listener demo");
        setLayout(new FlowLayout());
        setSize(300,300);
        setVisible(true);
        b = new Button("click me");
        b.addActionListener(this);
        add(b);
        addMouseMotionListener(this);

    }
    @Override
    public void actionPerformed(ActionEvent ae) {
        if(ae.getSource()== b){
            System.out.println("button clicked");
        }
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        System.out.println("mouse was dragged");
    }

    @Override
    public void mouseMoved(MouseEvent me) {
        System.out.println("mouse was moved");
    }
    
    public static void main(String[] args){
        new ListenersEvent();
    }
    
}        

In this program the Frame will look like this

Listener events

and the output will look somewhat like this

mouse was moved
mouse was moved
mouse was moved
mouse was moved
button clicked
mouse was dragged
mouse was dragged
mouse was dragged

Well this is just an example however the output you may observe will be according to your action on the frame. You will have to close the frame using either ctrl+c or stop icon on your IDE. Anyway let us divert our focus to the program and event.

First we have implement two type of listeners ActionListener and MouseMotionListener these relate to MouseEvent and ActionEvent class. Well, there is only one method in ActionListener interface and two in MouseMotionListener interface. As you already know that we have to implement all the method of an interface weather we want it or not.

We create frame and a button on the frame. Then we bind action listener with the button and MouseMotionListener with the Frame, so when we move or drag mouse on the Framed window we will be generating the events for MouseEvent type. Which may be handled in the corresponding method provided by the interface.

You might notice that we have done something with the action event in actionPerformed method. Well, getSource() is method provided in the class EventObject so it can be used on any type of the event class. Here we try and check if the action event was performed on the button we created. It is good in case you want to make sure the button action does not overlap.

We are done with the Listeners now let us tell you about the Adapters. Adapter are the classes which helps to reduce the code when we don't want all the method of an interfaces implemented. The methods in the adapter classes are same as in the interface but You need not to implemented all of them if you need only one or two In following program we are going to use anonymous class concepts to display the use of adapter class. We will be creating an inner class and and anonymous class which will help you reduce the code according to some level.


package events;

import java.awt.event.*;
import java.awt.*;

public class AdapterEvent extends Frame{
        
    AdapterEvent(){
        super("Adapter Event Demo");
        setSize(300,300);
        setVisible(true);
        setLayout(new FlowLayout());
        
        //event handling using anonymous class
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we){
                System.exit(0);
            }
        });
        
        addMouseMotionListener(new MouseInnerClass());
    }
    
    //Inner class to do event handling
    class MouseInnerClass extends MouseMotionAdapter{
        public void mouseDragged(MouseEvent me){
            System.out.println("mouse was dragged");
        }
    }
    
    public static void main(String[] args){
        new AdapterEvent();
    }
}

In this program we have created an Inner class and an anonymous inner class. The anonymous inner class creates a listener for the window event which will close the program when we create the frame by clicking close button.

adepter demo

mouse was dragged
mouse was dragged
mouse was dragged
mouse was dragged
mouse was dragged
mouse was dragged
mouse was dragged
mouse was dragged

We have added the windowListener to the frame and then we create a anonymous class inside that. This class uses the WindowApapter class and then override the windowClosing() method which takes the WindowEvent type reference as parameter. This will do for the anonymous class.

When we create Inner class for event handling all we need to do is to pass the object of the inner class when we bind the event. We are binding mouse motion listener with the frame and because we are going to use mouse motion adapter to accomplish the work we will be passing the object of inner class as the parameter in the binding method. rest remains same as the anonymous class.