- Mitra.ac.in

Download Report

Transcript - Mitra.ac.in

Programming in Java, 2e
Sachin Malhotra
Saurabh Choudhary
© Oxford University Press 2013. All rights reserved.
Chapter 13
Event Handling In Java
Objectives





Understand event delegation model
Understand what are events, sources,
and listeners
Know about their event classes and
associated listeners
how basic events are handled (in applets)
learn three ways of event handling:
Listeners, Adapters, and Inner classes
Introduction




We have done enough of objects and classes
by now.
An object resides in a particular state until it is
made to transit to other state.
This transition occurs due to an event.
For example, we want an object to invoke a
function when an action is generated, e.g.




pressing a key on the keyboard,
moving the mouse,
clicking on a button, etc.
The object which generates the event, i.e. the
source of the event is known as the event
generator.
Introduction

The object, responsible for performing the task
when an event occurs is called the event
handler.





There may be more than one event handlers for one
single event generated.
How do these handlers know that a particular
event has occurred so that they can perform
their activity?
There is a registration process, undertaken by
the event object, for each of its event handlers.
This registration involves the event handler
simply asking the event generator to inform
about the occurrence of an event.
By registering, the event generator is able to
keep track of all the registered event handlers.
Event Delegation Model





In Event Delegation Model, a source generates
events which are sent to one or more listeners.
The listeners receive the event, and process
them.
The processing logic applied for handling an
event is totally segregated by the logic that
generates the event, i.e. the event-generating
component can be designed differently than the
event-processing component.
Actually the event generating component
delegates the responsibility of performing an
event-based action to a separate eventperforming component.
The model has three dimensions, namely
events, event sources and event listeners.
Event Delegation Model




An event is an object that describes a state
change in the source.
It may be generated directly because of
interaction with the components of GUI
environment or any other reason such as expiry
of timer, completion of an operation, etc.
An event source is an object which generates
the event. Generation of event must cause a
change in the state of the source. A source can
generate more than one event.
Event Listeners are the objects that get notified
when an event occurs on an event source.
java.awt.AWTEvent


The java.awt.AWTEvent class is the root class
for all AWT Events.
java.awt.event packages includes the definition
of events classes, listeners interfaces, and
adapters classes, which from the basics for
event handling.
Event classes




Java has a predefined hierarchy of eventrelated classes, at the root of which is
EventObject.
It is actually a member of java.util package.
This class has constructors and methods
defined as its members.
One such constructor is EventObject(Object
src_obj)
 where, src_obj is the object, which generates
the event.
EventObject has methods like getSource() and
toString().
 getSource() – returns the source of the event
 toString() – returns the string equivalent of
the event
Event Classes (contd.)
ActionEvent



This event is generated by a component (such
as a Button) when the component-specific
action occurs (such as click).
The event is passed to an ActionListener object
which is registered to receive the event
notification
using
the
component’s
addActionListener method.
The object that inherits the ActionListener
interface is passed to the ActionEvent when an
event occurs. Some of the fields, constructors,
and methods associated with the ActionEvent
class
Field Summary of ActionEvent
Constructor of ActionEvent
Methods of ActionEvent
AdjustmentEvent

The adjustment events are generated by
Adjustable objects like scroll bar.
Fields of Adjustment Event
Constructor of AdjustmentEvent
Methods of AdjustmentEvent
KeyEvent

KeyEvent is an event which indicates that a
keystroke occurred in a component.




public class KeyEvent extends InputEvent
is generated by component object (such as a
text field, Applet, Frame) when a key is pressed,
released, or typed.
The event is passed to a KeyListener object
which is registered to receive the event
notification
using
the
component’s
addKeyListener method.
There can be three types of key events, which
are identified by integer constants.


KEY_PRESSED (it is generated when any key is
pressed)
KEY_TYPED (it is generated if a valid Unicode
character could be generated)
Few Integers constants in KeyEvent
Constructor
Methods in KeyEvent
MouseEvent


It is an event which indicates that a mouse
action occurred in a component.
A mouse action occurs in a particular
component if and only if the mouse cursor is
over the defined part of the component’s
bounds when the action happens.



public class MouseEvent extends InputEvent
There are eight types of mouse events defined
in the MouseEvent class.
The MouseEvent class defines them as integer
constants to identify each of these events.
Fields of MouseEvent
Constructors of MouseEvent
Methods of MouseEvent
FocusEvent


This event is generated when a component
gains or loses focus.
There are two types of focus events: permanent
and temporary.


Permanent focus event occurs when the user
explicitly changes focus from one component to
other, e.g. by pressing tab key.
Temporary focus event occurs when the focus is lost
due to operations like Window deactivated. In this
case, when the window will again be activated, the
focus will be on same component.
Fields of FocusEvent
Constructor of FocusEvent
Methods of FocusEvent
ItemEvent

It is an event which shows whether an item was
selected or de-selected.




public class ItemEvent extends AWTEvent
This event is generated by an ItemSelectable
object (such as a List), where the event is
generated when an item of the list is either
selected or de-selected.
The event generated is passed to every
ItemListener object which is registered to
receive such events.
The method addItemListener() is used for this
registration process.
Fields of ItemEvent
ItemEvent (contd.)
TextEvent

This event indicates the change in the object’s
text.



public class TextEvent extends AWTEvent
This event is generated by an object (such as a
TextComponent) whenever its text changes.
The event is passed to every TextListener
object which is registered to receive such
events.
The method addTextListener() is used for this
registration process.
TextEvent (contd.)
Source of Events








Button
Choice
MenuItem
List
Checkbox
Window
Scrollbar
Text Components
Source of Events



Event
Listeners
are
created
by
implementing one or more interfaces
defined by the java.awt.event package.
Whenever a source generates an event, it
basically invokes the appropriate method
defined in the listener interface.
The method has a event object passed as
an argument to it.
Listeners
KeyListener

This interface has three methods defined
within it.



void keyPressed(KeyEvent e) – invoked
when a key is pressed
void keyReleased(KeyEvent e) - invoked
when a key is released
void keyTyped(KeyEvent e) - invoked when a
character is typed
MouseListener

The interface has five methods, having
the signatures as follows:





void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
void mouseExited(MouseEvent e)
MouseMotionListener

The interface has two methods having the
signatures,



void mouseMoved(MouseEvent e)
void mouseDragged(MouseEvent e)
mouseMoved() is invoked when the mouse is
moved from one place to another and
mouseDragged() is used when the mouse is
dragged.
MouseWheelListener &
ItemListener

MouseWheelListener has only one
method, having the signature,


void mouseWheelmoved(MouseEvent e) invoked when the mouse wheel is moved.
ItemListener has only one method
defined as,

void itemStateChanged(ItemEvent e) invoked when the state of the item changes.
ActionListener, TextListener &
FocusListener

ActionListener has only one method


TextListener has only one method


void actionPerformed(ActionEvent e) - invoked when
any action event is performed.
void textChanged(TextEvent e) - invoked whenever
there is a change in text field or text area.
FocusListener interface has two methods,


void focusGained(FocusEvent e) - invoked when the
component obtains keyboard focus and focusLost()
void focusLost(FocusEvent e) - is invoked when the
component looses the keyboard focus.
WindowListener

This interface has seven methods







void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowOpened(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowIconified(WindowEvent e)
void windowDeiconified(WindowEvent e)
Model


Each source, generating the events must register event
listeners to itself, so that listeners get the license for
receiving the events from the respective source.
Each type of event has its own registration method,
having the form,


These listeners, once registered for events from a
particular source, can get unregistered also using


public void addTypeListeners(TypeListener tl)
public void removeTypeListener(TypeListerner tl)
Once the listener objects are registered, they must
implement the methods to receive and process the
event notifications sent by source.
Example (MouseMotionListener)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseMotionEx extends Applet
implements MouseMotionListener {
int xcord, ycord;
public void init()
{ addMouseMotionListener(this);
}
Continued
public void paint(Graphics g)
{
g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,yc
ord);
}
public void mouseMoved(MouseEvent me)
{ xcord = me.getX();
ycord = me.getY();
repaint();
}
public void mouseDragged(MouseEvent me){}
}
Another way of doing same
/*<applet code = “MouseMotionEx.class” width = 700
height = 700 > </applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseMotionEx extends Applet
{
int xcord; int ycord;
public void init(){
addMouseMotionListener (new Demo(this));}
public void paint (Graphics g){
g.drawString (“(“+x cord +”, “+y cord+”)”);
}}
`
Another way of doing same (contd.)
class Demo implements MouseMotionListener
{
MouseMotionEx m;
Demo(MouseMotionEx m)
{
this.m=m;
}
public void mouseMoved(MouseEvent me) {
m.xcord = me.getX();
m.ycord = me.getY();
m.repaint();}
public void mouseDragged(MouseEvent me)
{}
Adapter classes






In listener interfaces, you have to implement all the
methods defined in that interface
This can be annoying at times, particularly when you
need to implement methods of the interface, which
might not actually be used.
In order to simplify things, Java came up with the
concept of adapter classes.
JDK defines corresponding adapter classes for listener
interfaces containing more than one methods e.g. for
MouseMotionListener, MouseMotionAdapter class has
been defined.
Adapter classes provide empty definitions for all the
methods of their corresponding Listener interface.
It means that MouseMotionAdapter class inherently
implements MouseMotionListener interface.
Adapter classes
How to use Adapter classes?
/*<applet code=”AdapterDemo.class” width=300
height=300></applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AdapterDemo extends Applet {
int xcord,ycord;
public void init(){
addMouseMotionListener(new
MouseDemo(this));
}
public void paint(Graphics g){
g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,ycord
);
}}
The Output
Inner classes

An inner class can be defined and instantiated all inside
a class, or even within an expression.




member classes,
local classes, and
annoymous classes.
Member classes




are included in the class definition just like fields and
methods.
can either be static or instance.
Static member class: A member class can be static
with access only to the static members of the class to
which it belongs.
Instance member class: A member class can be
instance with access to both the static and instance
members of the class that contains it.
Inner classes (contd.)

Local classes


A local class is defined within a code block, typically
in a method. An instance of a local class exists only
during the execution of the method
Anonymous Inner classes




An anonymous inner class is one that is not
assigned a name.
Such classes are created on the fly i.e. they are
created, instantiated, used and garbage collected
when they are done.
They are automatically assigned a name as
Outerclassname$1.
This anonymity helps in eliminating the unnecessary
named objects. Besides, it makes the program more
readable.
Use of Member Inner Class
/*<applet code = OuterClass.class width=600
height=600> </applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class OuterClass extends Applet {
public void init()
{
addKeyListener(new InnerClass());
}
class InnerClass extends KeyAdapter {
public void keyPressed(KeyEvent ke) {
showStatus(“key down”);
}
public void keyReleased(KeyEvent ke){
showStatus(“key up”);
}}}
Use of Anonymous Inner Class
/*<applet code=”AnonyKeyListDemo.class”
width=300 height=300> </applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AnonyKeyListDemo extends Applet {
public void init(){
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent ke){
showStatus(“Key Pressed”);}
public void keyReleased(KeyEvent me){
showStatus(“Key Released”); }
});
}}
The Output
Summary





In this chapter, we have emphasized on the
features that enhance the GUI capabilities of
Java by using Event Handling.
Event Handling model has been discussed.
The modern approach to event handling uses
Event Delegation Model where a source
generates events, which are sent to one or
more listeners.
These Listeners receives the event notifications,
which are handled as required by the different
methods of event classes.
All Three approaches for event handling have
been discussed


Listener interfaces
Adapter classes