Events

Event is an object that describes a state of change in a source.

May be generated as a consequence of a person interacting with the GUI elements
Pressing a button.
Entering a character through keyboard
Selecting an item from a list

May also be generated that are not directly caused due to user interactions
Timer expires
Counter exceeds a value

Event Sources

  • "Source" is an object that generates an event.
  • The modern approach to handling events is based on the delegation event model.
  • In this model source generates an event and sends it to one or more listeners.
  • In this scheme, the listener simply waits until it receives an event.
  • Once received, the listener processes the event and then returns.
  • The advantage of this design is that the application logic that processes events is clearly separated from the user interface logic that generates those events.
  • A user interface logic is able to delegate the processing of an event to a separate piece of code.
  • In the delegation model, listeners must register with the source in order to receive event notification.
  • An each type of event has its own registration method and following is the general form of it.
    public void addTypeListener(TypeListener el);
  • Here type is the name of the event and el is the reference to the event listener. For example the, the method that registers a keyboard event listener is called:addkeyListener().
  • The method that registers a mouse motion listener is called:addMouseMotionListener()
  • There is also a method that allows a listener to unregister an interest in a specific type of event.
  • public void removeTypeListener(TypeListener el);
    removeKeyListener();

Event Listeners

  • A listener is an object that is notified when an event occurs.
  • To do so 2 things should be satisfied.
        -It must have been registered with one or more sources to receive notification.
        -It must implement methods to receive and process these notifications.
  • The mentioned methods are defined in a set of interfaces found in java.awt.event package

Steps to Handle Events

  • Declare and instantiate event sources (or components) such as buttons, menus, choices etc.
  • Implement an interface (listener) to provide the event handler that responds to event source activity.
  • Register this event handler with the event source.
  • Add the event source to the container like applet, frame, panel etc.

Event Delegation Model



  • An event source produces events and dispatches them to all registered event listeners.
  • A single class can implement multiple listener interfaces.
  • A single listener object can register with multiple event sources.
  • Multiple listener objects can register with a single event source (multicast).

Event Class

Click here for .java code.

Click here for .html code.

There are many event classes and these are the core of Java,s event handling mechanism.

Few of the classes are ActionEvent, FocusEvent, InputEvent, keyEvent, MouseEvent, WindowEvent etc.

ActionEvent class:

An ActionEvent is generated when a button is pressed, a list item is double clicked, or a menu item is selected ActionListener interface defines one method to receive action events. The method is actionPerformed() is invoked when an action event occurs.
Syntax is:
     void actionPerformed(ActionEvent ae)

Event Delegation Model


WindowListener


interface WindowListener extends EventListener
{ 
	public void windowClosing(WindowEvent e);
	public void windowClosed(WindowEvent e); 
	public void windowOpened(WindowEvent e);
	public void windowIconified(WindowEvent e);
	public void windowDeIconified(WindowEvent e);
	public void windowActivated(WindowEvent e);
	public void windowDeacivated(WindowEvent e);
}

Steps to handle events: (Event Delegation Model)

  • Implement the appropriate Listener Interface
    public class MyAdapter implements XXXListener
    {
         // override and implement all XXXListener methods.
    }
  • Register this handler with the event source ( or component)
    component.addXXXListener(new MyAdapter);

In this following program all the methods of the Interface have overridden and it is necessary

Click here for example.

Click here for .java code.

Click here for .html code.

Problem with Listener Interface

  • Although interested in handling only one event, you should implement all the methods declared in the listener interface.
    Ex: WindowListener.
  • Can it be solved in some way?
    Yes. -->Listener Adapters
  • Adapter classes implement the corresponding Listeners by giving null implementations to all methods of that Listener.
  • Declare your event handler as a subclass of this adapter.
  • When using Adapters, instead of Listeners, selective method overriding is possible.

Adapter classes

  • ComponentAdapter ---- ComponentListener
  • MouseMotionAdapter ---- MouseMotionListener
  • MouseAdapter ---- MouseListener
  • WindowAdapter ---- WindowListener
  • ContainerAdapter ---- ContainerListener
  • FocusAdapter ---- FocusListener
  • KeyAdapter ---- KeyListener

WindowAdapter


public abstract class WindowAdapter implements WindowListener
{
	public void windowClosing(WindowEvent e){ }
	public void windowClosed(WindowEvent e) { }
	public void windowOpened(WindowEvent e){ }	
	public void windowIconified(WindowEvent e){ }
	public void windowDeIconified(WindowEvent e){ }
	public void windowActivated(WindowEvent e){ }
	public void windowDeacivated(WindowEvent e){ }
}


Using WindowAdapter class


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class TestFrameEvent2 extends WindowAdapter
{
	Frame f;
     	TestFrameEvent2()
	{
     		f=new Frame("New Frame");
     		f.setSize(300,200);
     		f.setVisible(true);
     		f.addWindowListener(this);
      	}
   	public void windowClosing(WindowEvent e)
        {
		System.out.println("Windows is closing");
                System.exit(0);
        }
	public static void main(String args[])
	{
      		TestFrameEvent2 tf=new TestFrameEvent2();
       	}
}

In this example WindowsAdapter class is used when you are interested only in one event say windowClosing() event.

Using Anonymous Inner class

Click here for .java code.

Click here for .html code.

The size of the program can be reduced by using inner classes. They allow you to put the event handling class and method right next to the place where you declare the control or register the call back listener. Anonymous classes are the refinement of inner classes allowing you to combine the definition of the class with the instance allocation.

An anonymous inner class is one that is not assigned a name. Let us consider an applet which will display a string "Mouse Pressed" in the status bar of the applet viewer or browser when the mouse is pressed.

There is one top level class in this program: AnonymousInnerClassDemo. The init() method calls the addMouseListener() method. Its argument is an expression that defines and instantiates an anonymous inner class.

The syntax new MouseAdapter() {...} indicates to the compiler that the code between the braces defines an anonymous inner class.

Furthermore that class extends Mouse Adapter. This new class is not named, but it is automatically instantiated when this expression is executed.

Because this anonymous inner class is defined within the scope of AnonymousInnerClassDemo, it has access to all of the variables and methods within the scope of that class. Therefore, it can call showStatus() method directly.

Thus you can create more efficient code.


Java Applet << Previous

Our aim is to provide information to the knowledge


comments powered by Disqus




Footer1