Event Handling in Java



Event Handling in Java

The GUI in Java processes the interactions with user via mouse; keyboard and various user controls such buttons, checkbox, text-field etc. as the events. These events are to be handled properly to implement Java Programming as an Event-Driven Programming.

[pic]

FIG: Event-Driven Programming

Delegation Event Model

• Modern approach to handle event which defines standard and consistent mechanisms to generate and process events

• Concept in Delegation Model:

• A source generates an event and sends it to one or more listeners

• Listener waits until it receives an event

• When Listener receives an event , it processes and then returns

• Major advantage of this model is that the event handling model code can be separately maintained from those which generate the event.

• In this model each listener should be assigned to the source in order to receive an event notification

• So another advantage that can be realized is that the events can be sent only to those listeners that are required to receive them

• In traditional event handling mechanism, an event was propagated up the containment hierarchy until it was handled by a component which required the components to receive events that they did not process and wasted the valuable time.

Components in Event Handling

• Events

• Event Sources

• Event Listeners/ Handlers

Events

• Defined as an object that describes a change in state of a source object

• Java defines a number of such Event Classes inside java.awt.event package

|Event Classes |Description |

|ActionEvent |Generated when a button is clicked, List item is double clicked, Menu Items is selected |

|AdjustmentEvent |Generated when a Scroll Bar is manipulated |

|ComponentEvent |Generated when a Java Components is hidden,moved, resized, or becomes visible |

|ContainerEvent |Generated when a component is added to or removed from Containers |

|FocusEvent |Generated when a component gains or looses keyboard focus |

|InputEvent |Abtract super class for all components input event classes such as KeyEvent and MouseEvent |

|ItemEvent |Generated when a checkbox or item list is clicked and also occurs when a choice selection is made or a checkable menu |

| |item is selected or deselected |

|KeyEvent |Generated when input is received from the keyboard |

|MouseEvent |Generated when the mouse is dragged, moved, clicked, pressed, released; also occurs when mouse enters or exits a |

| |component |

|MouseWheelEvent |Generated when the mouse wheel is moved |

|TextEvent |Generated when a values of text component change |

|WndowEvent |Generated whena window is activated, closed, deactivated, deiconified, iconified, opened or quit |

Event Source

• A source is an object that generates an event

• Event generation occurs when internal state of that object changes in some way

• A source must register listeners in order for the listeners to receive the notifications about a specific type of events

• General form of adding such listeners:

o public void addTypeListener(TypeListener obj)

o Eg:

Button btnObj=new Button("Enter");

btnObj.addActionListener(el);

//el is the object of class that implements ActionListener interface

|Event Source |Description |

|Button |Generates ActionEvent when button is pressed |

|Checkbox |Generates ItemEvent when the checkbox is selected or deselected |

|Choice |Generates ItemEvent when the choice is changed |

|List |Generates ActionEvent when an item is double-clicked; generates ItemEvent when an item is selected or |

| |deselected |

|Menu Item |Generates ActionEvent when a menu item is selected and when a checkable menu item is selected or |

| |deselected |

|Scroll bar |Generates AdjustmentEcent when the scroll bar is manipulated |

|Text Component |Generates TextEvent when the user enter a character |

|Window |Generates WindowEvent when a window is activated, closed, deactivated, deiconified, iconified, opened |

| |or quit |

Event Listeners

• A listener is an object that is notified when an event occurs

• It has two major requirements:

o It should be registered to one more source object to receive event notification

o It must implement methods to receive and process those notifications

• Java has defined a set of interfaces for receiving and processing the events under the java.awt.event package

|Event Listener Interface |Description |Methods Provided |

| | |(Default void return type for all methods) |

|ActionListener |Defines one method to receive ActionEvent |actionPerformed(ActionEvent ae) |

|AdjustmentListener |Defines one method to receive |adjustmentValueChanged (AdjustementEvent ae) |

| |AdjustementEvent | |

|ComponentListener |Defines four methods to recognize when a |componentResized(ComponentEvent ce) |

| |component is hidden, moved, resized, or shown|componentMoved(ComponentEvent ce) |

| | |componentShown(ComponentEvent ce) |

| | |componentHidden(ComponentEvent ce) |

|ContainerListener |Defines two methods to recognize when a |componentAdded(ContainerEvent ce) |

| |component is added to or removed from a |componentRemoved(ContainerEvent ce) |

| |container | |

|FocusListener |Defines two methods to recognize when a |focusGained(FocusEvent fe) |

| |component gains or loses keyboard focus |focusLost(FocusEvent fe) |

|ItemListener |Defines one method to recognize when the |itemStateChanged(ItemEvent ie) |

| |state of an item changes | |

|KeyListener |Defines three methods to recognize when a key|keyPressed(KeyEvent ke) |

| |is pressed, released or typed |keyReleased(KeyEvent ke) |

| | |keyTyped(KeyEvent ke) |

|MouseListener |Defines five methods to recognize when mouse |mouseClicked(MouseEvent me) |

| |is clicked, enters a component, exits a |mouseEntered(MouseEvent me) |

| |component, is pressed or is released |mouseExited(MouseEvent me) |

| | |mousePressed(MouseEvent me) |

| | |mouseReleased(MouseEvent me) |

|MouseMotionListener |Defines two methods to recognize when the |mouseDragged(MouseEvent me) |

| |mouse is dragged or moved. |mouseMoved(MouseEvent me) |

|MouseWheelListener |Defines one method to recognize when the |mouseWheelMoved(MouseWheenEvent me) |

| |mouse wheel is moved | |

|TextListener |Defines one method to recognize when a text |textChanged(TextEvent te) |

| |value changes | |

|WindowFocusListener |Defines two methods to recognize when a |windowGainedFocus(WindowEvent we) |

| |window gains or loses input focus |windowLostFocus(WindowEvent we) |

|WindowListener |Defines seven methods to recognize when a |windowActivated(WindowEvent we) |

| |window is activated, closed, deactivated, |windowClosed(WindowEvent we) |

| |deiconified,, iconified, opened or quit |windowClosing(WindowEvent we) |

| | |windowDeactivated(WindowEvent we) |

| | |windowDeiconified(WindowEvent we) |

| | |windowIconified(WindowEvent we) |

| | |windowOpened(WindowEvent we) |

Event Handling Mechanisms in Java

• Using Delegation Event Model

• Using Adapter Classes

• Using Inner Classes

• Using Anonymous Inner Classes

Using Delegation Event Model

• Steps followed in Delegation Event Model for event handling in Java:

1. Implement the appropriate interface in the listener so that it will receive the type of event desired

2. Implement code to register the listener as a recipient for the event notifications

• Example Code:

//Demonstration of Delegation Event Model for Event Handling In Java

//DelegationEventModel.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class MyActionHandler implements ActionListener //Creating a Action Listener of our own

{

DelegationEventModel myFrame;

MyActionHandler(DelegationEventModel frme)

{

myFrame=frme;

}

public void actionPerformed(ActionEvent ae)

// Implementing the method of ActionListener Interface

{

myFrame.tObj.setText("You Just Pressed The Button");

myFrame.btnObj.setVisible(false);

}

}

class DelegationEventModel extends Frame implements KeyListener

// Implementing Key Listener within Frame itself

{

Button btnObj;

Panel pnlObj;

TextField tObj;

MyActionHandler myAction;

DelegationEventModel(String str)

{

super(str);

myAction=new MyActionHandler(this); //creating object of MyActionHandler

setLayout(new FlowLayout());

btnObj=new Button("OKAY");

pnlObj=new Panel();

pnlObj.setLayout(new FlowLayout());

tObj=new TextField("Check This Out",50);

tObj.setEnabled(false);

pnlObj.add(btnObj);

pnlObj.add(tObj);

btnObj.addActionListener(myAction); //Registering Action Listener for the Button

add(pnlObj);

addKeyListener(this); //Register itslef as the key Listener for the Frame

setVisible(true);

setSize(500,200);

}

public void keyTyped(KeyEvent ke)

// Implementing the method of KeyListener Interface

{

JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());

btnObj.setVisible(true);

}

public void keyReleased(KeyEvent ke)

// Implementing the method of KeyListener Interface

{

//setTitle("Key Up");

}

public void keyPressed(KeyEvent ke)

// Implementing the method of KeyListener Interface

{

//setTitle("Key Down");

}

public static void main(String[] args)

{

DelegationEventModel objMain=new DelegationEventModel("Delegation Event Model for Event Handling");

}

}

Using Adapter Classes

• In the above example, while implementing an interface for listener there is a overhead of implementing all the methods provided by the interface even if we don’t want to

• For EG: when we implement KeyListener interface then we should give the implementation code for all three methods provided by this interface as in above example

• At times we might not need to implement all methods of those interface class, and this is done in Java by the special feature named Adapter classes

• Adapter Classes are the classes which provided the empty implementation of an the event listener interface that it is associated with

• For an instance KeyAdapter is an adapter class for keyListener interface and the structure of that KeyAdapter class looks like:

class KeyAdapter implements KeyListener

{

void keyTyped(KeyEvent ke)

{

}

void keyReleased(KeyEvent ke)

{

}

void keyPressed(KeyEvent ke)

{

}

}

• Now if we extend KeyAdapter Class instead of implementing KeyListener Interface, then only required methods can be overridden

• For Eg:

class MyActionHandler extends KeyAdapter

{

void keyTyped(KeyEvent ke)

{

//required codes

}

}

class MainClass extends Frame

{

MainClass()

{

super("My Frame");

MyActionHandler myAction=new MyActionHandler();

addKeyListener(myAction);

}

public static void main(String[] args)

{

//Main function codes

}

}

Program Demo Example for Using Adapter Class

//Demonstration of Adapter Classes for Event Handling In Java

//UsingAdapter.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class MyActionHandler extends KeyAdapter

//Creating a Action Listener of our own using Adapter Class

{

UsingAdapter myFrame;

MyActionHandler(UsingAdapter frme)

{

myFrame=frme;

}

public void keyTyped(KeyEvent ke)

// Overriding the required method only of KeyAdapter Class

{

JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());

myFrame.btnObj.setVisible(true);

}

}

class UsingAdapter extends Frame implements ActionListener

// Implementing Action Listener within Frame itself

{

Button btnObj;

Panel pnlObj;

TextField tObj;

MyActionHandler myAction;

UsingAdapter(String str)

{

super(str);

myAction=new MyActionHandler(this); //creating object of MyActionHandler

setLayout(new FlowLayout());

btnObj=new Button("OKAY");

pnlObj=new Panel();

pnlObj.setLayout(new FlowLayout());

tObj=new TextField("Check This Out",50);

tObj.setEnabled(false);

pnlObj.add(btnObj);

pnlObj.add(tObj);

btnObj.addActionListener(this); //Registering Action Listener for the Button

add(pnlObj);

addKeyListener(myAction); //Register itslef as the key Listener for the Frame

setVisible(true);

setSize(500,200);

}

public void actionPerformed(ActionEvent ae)

// Implementing the method of ActionListener Interface

{

tObj.setText("You Just Pressed The Button");

btnObj.setVisible(false);

}

public static void main(String[] args)

{

UsingAdapter objMain=new UsingAdapter("Adapter Class for Event Handling");

}

}

Commonly Used Listener Interfaces Implemented By The Adapter Classes

|Adapter Class |Listener Interface |

|ComponentAdapter |ComponentListener |

|ContainerAdapter |ContainerListener |

|FocusAdapter |FocusListener |

|KeyAdapter |KeyListener |

|MouseAdapter |MouseListener |

|MouseMotionAdapter |MouseMotionListener |

|WindowAdapter |WindowListener |

Using Inner Classes for Event Handling

• Class defined within other class or even within an expression is inner class

• Event handling in this method is carried out by an inner listener class defined within the class with the GUI Components

• Example Code:

//Demonstration of Adapter Classes for Event Handling In Java

//UsingInner.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class UsingInner extends Frame implements ActionListener

// Implementing Action Listener within Frame itself

{

Button btnObj;

Panel pnlObj;

TextField tObj;

MyActionHandler myAction;

UsingInner(String str)

{

super(str);

myAction=new MyActionHandler(this); //creating object of MyActionHandler

setLayout(new FlowLayout());

btnObj=new Button("OKAY");

pnlObj=new Panel();

pnlObj.setLayout(new FlowLayout());

tObj=new TextField("Check This Out",50);

tObj.setEnabled(false);

pnlObj.add(btnObj);

pnlObj.add(tObj);

btnObj.addActionListener(this); //Registering Action Listener for the Button

add(pnlObj);

addKeyListener(myAction); //Register itslef as the key Listener for the Frame

setVisible(true);

setSize(500,200);

}

public void actionPerformed(ActionEvent ae)

// Implementing the method of ActionListener Interface

{

tObj.setText("You Just Pressed The Button");

btnObj.setVisible(false);

}

public static void main(String[] args)

{

UsingInner objMain=new UsingInner("Inner Class for Event Handling");

}

class MyActionHandler extends KeyAdapter

//Creating an Inner Action Listener of our own using Adapter Class

{

UsingInner myFrame;

MyActionHandler(UsingInner frme)

{

myFrame=frme;

}

public void keyTyped(KeyEvent ke)

// Overriding the required method only of KeyAdapter Class

{

JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());

myFrame.btnObj.setVisible(true);

}

}

}

Using Anonymous Inner Classes

• An anonymous inner class is one that is not assigned a name and is defined inside an expression

• For event handling anonymous listener classes are defined while registering listener to the source

• For Eg:

Button myBtn =new Button("Sample");

myBtn.addActionListener( new ActionListener()

{

public void actionPerformed(ActionEvent ae)

{

//tasks to do

}

});

• General Structure is as:

eventSource.addTypeListener(new TypeListener()

{

//implement the methods within TypeListener Interface

});

Example Code

//Demonstration of Adapter Classes for Event Handling In Java

//UsingAnonymous.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class UsingAnonymous extends Frame

{

Button btnObj;

Panel pnlObj;

TextField tObj;

MyActionHandler myAction;

UsingAnonymous(String str)

{

super(str);

myAction=new MyActionHandler(this); //creating object of MyActionHandler

setLayout(new FlowLayout());

btnObj=new Button("OKAY");

pnlObj=new Panel();

pnlObj.setLayout(new FlowLayout());

tObj=new TextField("Check This Out",50);

tObj.setEnabled(false);

pnlObj.add(btnObj);

pnlObj.add(tObj);

btnObj.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent ae)

// Implementing the method of ActionListener Interface

{

tObj.setText("You Just Pressed The Button");

btnObj.setVisible(false);

}

}); //Registering and implementing Anonymous Action Listener for the Button

add(pnlObj);

addKeyListener(myAction); //Register itslef as the key Listener for the Frame

setVisible(true);

setSize(500,200);

}

public static void main(String[] args)

{

UsingAnonymous objMain=new UsingAnonymous("Anonymous Inner Class for Event Handling");

}

class MyActionHandler extends KeyAdapter

//Creating an Inner Action Listener of our own using Adapter Class

{

UsingAnonymous myFrame;

MyActionHandler(UsingAnonymous frme)

{

myFrame=frme;

}

public void keyTyped(KeyEvent ke)

// Overriding the required method only of KeyAdapter Class

{

JOptionPane.showMessageDialog(null,"Key Typed "+ke.getKeyChar());

myFrame.btnObj.setVisible(true);

}

}

}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download