0% found this document useful (0 votes)
5 views14 pages

Java Event Handling

This document provides a comprehensive overview of event handling in Java programming, focusing on user interaction through events generated by actions such as mouse clicks and keyboard inputs. It discusses the Java 1.0 Event Model and the Delegation Event Model, detailing event sources, event listener interfaces, and various event classes. The document also outlines the methods for handling different types of events, emphasizing the importance of registered listeners in processing these events.

Uploaded by

rajasingh756023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Java Event Handling

This document provides a comprehensive overview of event handling in Java programming, focusing on user interaction through events generated by actions such as mouse clicks and keyboard inputs. It discusses the Java 1.0 Event Model and the Delegation Event Model, detailing event sources, event listener interfaces, and various event classes. The document also outlines the methods for handling different types of events, emphasizing the importance of registered listeners in processing these events.

Uploaded by

rajasingh756023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Event Handling

UNIT 11 EVENT HANDLING


Structure
11.0 Introduction
11.1 Unit Objectives
NOTES
11.2 Events
11.3 Event Handling Model
11.3.1 Java 1.0 Event Model
11.3.2 Delegation Event Model
11.4 Event Handling
11.4.1 Event Classes
11.4.2 Event Sources
11.4.3 Event Listener Interfaces
1144 Adapter Classes
11.5 Summary
11.6 Key Terms
11.7 Answers to 'Check Your
Progress'
11.8 Questions and Exercises

11.0 INTRODUCTION
Java applets are used to create
graphical and user-interactive applications. The applets
designed so far were graphical in nature but did very little when it comes to demonstrating
their user-interactive capability. User interaction means a
specific action is generated
and an appropriate result is displayed to the user when he interacts with an
application
say by clicking mouse or enteringa character using the keyboard. In Java, all the activities
that occur between the user and the application are termed as events. Events play a
significant role in applet programming as they facilitate to include user-interactivity in
applets.
In this unit, you will get a
comprehensive overview of event handling in Java
programming.

11.1 UNIT OBJECTIVES

After going through this unit, you will be able


to
Understand what an event is
Learn about the model on which Java event
handling mechanism is based, with
special emphasis on Java 1.0 event model and delegation event model
Understand aboutevent handling, event classes, event sources and event listener
interfaces
Learn how handle various events such as key press
to
the
clicks, mouse events and so on
on
keyboard, button

11.2 EVENTS
InJava, an event is an object which specifies the change of state in the source. It is
generated whenever an action takes place like a mouse button is clicked or text is
modified. Java's AWT (Abstract Window Toolkit) is
these actions between the program and the user. Java
responsible for communicating
packages such as [Link],
Self-Insructional
AMaterial 143
ort event handling
support event
Event Handling [Link]

and
[Link], [Link]. event
mechanism. event and all.
Thegenerated
is generated. ofevent, etc.
a n event are sent to the
When an action takes place, type
nformation about it such as timeofits n. This
occurrence,

This code
code determines
NOTES within the
program.
response cani be sent to
appropriate event handling code provided appropriate
how the allocated event will behandled sothat an
the user.

11.3 EVENT HANDLING MODEL


is govemed byits
underlying -handling
event-ha

The working of an event-drivenjprogram


introduced in
Java forreceivingand processing
model. Till now two models havebeen differa lot from
models
other. In
each«
events. The eventhandling mechanisms ofthese models is discussed.
the two event
the 1OloWng section, a comparison between

11.3.1 Java 1.0 Event Model


on the concept ofcontainment,
was based
Java 1.0 Event model for event processing it is fist sent to
the component
he user-initiated event is generated
when a at this component
n tis approach, case the event
is not handled
the event has occurred. But in This process Is Continued
wnich container ofthat component.
TIs automatically propagated to the containment hierarchy.
until the event is processed or it
reaches the root of the
contained in the Panelwhich
as shown in the Figure
11.1, Button is
Forexample, When the mouse is
clicked on Button, an event is
tSelfis contained within the Frame. it then this event is
not handled by
which is first sent to the Button. If it is
generated further sent to the Frame
forwarded to the Panel and ifit cannot
handle the event, it is
this event. Sothe event is forwarded
Frame being the root ofthe given hierarchy processes
until it is handled by a component.
up the containment hierarchy
Event Handled at

Frame
Frame
Unhandled Event
Panel Propagated

Button Event Generated


at Button

Figure 11.1 Java 1.0 Event Handling Mechanism

be handled by the
major drawback in this approach is that events could
The
container of that component. Another problem is
component that generated it or by the
that events are frequently sent to those components that cannot process them, thus
wasting a lot of CPU cycles.

11.3.2 Delegation Event Model


The advanced versions of Java ruled out the limitations of Java 1.0 event model. This
model is referred to as the Delegation Event Model which defines a logical approach
to handle events. It is based on the concept of source and listener. A source generates
an event and sends it to one or more listeners. On receiving the event, listener processes
the event and returns it. The notable feature of this model is that the source has a
registered list of listeners which will receive the events as they occur. Only the listeners
Self-Instructional
144 Material
that have been registered actually receive the notification when a specific event is Event Handling

generated

For example, as shown in the Figure 11.2, when the mouse is clicked on Button,
an event is generated. If the Button has a registered listener to handle the event, this
event is sent to Button, processed and the output is returned to the user. However, ifit NOTES

has no registered listener the event will not be propagated upwards to Panel or Frame.

Frame

Panel
Event Handler

Button
Event Generated

Figure 11.2 Java 1.1 Event Handling Mechanism

Now we discuss Event Source and Event Listener in detail.


Event Source: An event is
source an object that generates a particular kind of,
event. An event is generated when the internal state of the event source is changed. A
source may generate more than one type of event. Every source must register a list of
listeners that are interested to receive the notifications regarding the type of event.
Event sourceprovides methods to add or remove listeners.
The general form of method to register (add) a listener is
public void adaTypeListener (TYpeListener eventlistener)
Similarly, the general form of method to unregister (remove) a istener is
public void removeTYpeListener (TYpeListener
eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
Event Listener: An event listener is an
object which receives notification when
an event occurs. As already mentioned, only registered listeners can receive
from sources about specific types of events. The role of event listener notifications
is to receive
these notifications and process them.
-

11.4 EVENT HANDLING


Java provides various classes and interfaces to handle the
these are discussed in this section. generated events. Some of
11.4.1 Event Classes
Java 1.1 event classes
encapsulate all types of events occurring in the system. A
successful handling of the events requires
these classes have been
in-depth understanding of these classes. Al
arranged in a hierarchy having Eventobject class as its
root element. This class acts as the
class belongs to [Link]
superclass of all the event classes. Event0bject
package. Some of the event classes along with their
description are listed in Table 11.1.

Self-Instructional
Material 145
Classes
Event
Event Hundling Table 11.1
Description
uscr selectsa menv
when a
gencratcd
that is
Class the event a list item.
double-clicks
represents

ActionEvent I button or

ilem, presses
when a
change has occ
occuTed i
inteon
NOTES cvent
that is
generated
class
defines an

It represents
an
tEvent that signals thatsome
AdjustmentEvent the
The
Adjustmen
ADJUSTMENT_VALUE_CHANGED
serollbar.

constant,
when a menu ite
changehas occurred. which is generated
clicked or a list it 1
the cvcnt
item is
m is
represcnts checkbox
ItemEvent lt desclectod.
selected o r interacts
the user
when
sclected. event that is
gencratcd

represents
the
l interacts
KeyEvent application through
keys.
generaled
when the u s e r
with|
the event that is
the
It represents
mouse. enter
MouseEvent through the when the user ters or
the applicationthc event
generated
that is
lt
textareas,
represents
TextEvent of the wind.
text fields or when the
state
changes textin cvent that is generated
the
lt represents

WindowEvent bean when 1the property


changes. that is generated
by a
the event
lt represents
|PropertyChangeEvent| changes. the event
associatcd with it also represents
about the
P r o p e r t y C h a n g e E v e n t

notifies
This class like but it only
| ChangeEvent of an object
on the change
generated
object. the text component
change ofthesource
event which
is generated by
the or when
some text is
It represents its position
CaretEvent when the caret (crusor) changes
selected.

11.4.2 Event Sources Some of the


which generate events.
sources are the objects
As stated earlier, event
11.2.
listed in the Table
examples ofeventsources
are

Sources
Table 11.2 Event
Description
Event Souree pressed.
events when the button is
generates action
Button window changes.
events when the
state of the
generates window
Window entered in text field or
text area.
events when a text is
generates text
Text components -

events when a menu


item is selected, generates
item
generates action
Menu item menuisselected or deselected.
events when a checkable
when a checkbox is selected
or deselected.
generates item events
Checkbox generates
generates action events when an item is double-clicked,
List when an item is selected or deselected.
action events manipulated.
events when the scroll bar is
generates
Scrollbar

11.4.3 Event Listener Interfaces


are sent to event listeners which handle them in
Events generated by the event source
listeners implement various interfaces. Some of the
an appropriate manner. Event
interfaces are discussed here.

The ActionListener Interface


() method defined by the
When an action event occurs, the action Performed
ActionListener interface is invoked.
is
The general form of the action Performed () method
void actionPerformed (ActionEvent e)

Self-Instrucunul
146 Matriul
where,
e is the reference to an Event Handling
object of
The AdjustmentListener Interface ActionEvent class
When an adjustment event
occurs, the
adjustmentValueChanged
defined by the AdjustmentListener
interface is invoked.
() method NOTES
The general form ofthe
void adjustmentValueChanged () method
adjustmentValueChanged is

where, (AdjustmentEvent e)

e is the
reference to an object
of
The ItemListener Interface AdjustmentEvent class
The method
invoked when the
itemStateChanged
state of
() defined by the
ItemListener intertace
an item is changed. The is
passed as method parameter. object of ItemEvent class is

The general form


of the method defined in
void ItemListener interface is
itemStateChanged (ItemEvent item)
The KeyListener Interface
The methods defined by the
KeyListener interface are invoked when any key is
pressed or released, or a character is entered. The
as method parameter. object of KeyEvent class is passed
The general form
of the methods defined in
void
keyPressed (KeyEvent key) KeyListener interface is
void keyReleased
(KeyEvent key)
void keyTyped
(KeyEvent key)
Note: If a key B is pressed and
and key released)
released, three events (key pressed, key typed
are
generated.
The MouseListener Interface and MouseMotionListerer
Interface
The methods defined by the MouseListener
interface are invoked when the mouse
is clicked, pressed, released, when the mouse
enters or exits the
the methods defined by the component. Similarly,
MouseMotionListener interface are invoked when
the mouse is dragged or moved from one
class is passed as method
position to another. The object ofMouseEvent
parameter.
The general form of the methods defined in
MouseListener interface is
void mousePressed (MouseEvent me)
void mouseReleased (MouseEvent me)
void mouseclicked (MouseEvent me)
void mouseEntered (MouseEvent me)
void mouseExited (MouseEvent me)

The general form of the methods defined in MouseMotionListener


interface
IS

void mouseMoved (MouseEvent me)


void mouseDragged (MouseBvent me)

'Self-Instructionul
Material 147
Event Handling
The TextListener Interface
The method
invoked when
unvoked textValueChanged () defincd by the
t
when the text inside tthe text arca or text Gcid
ficld
TextListener

alters. The object


altcrs. The oj of
interfacc is
interfacei.
Text
NOTES class is passed as
method parameter.
tEvent
egeneral fom ofthe method defined in TextListener interface is
void textValueChanged (TextEvent te)
The WindowListener Interface
Demethods defined by the WindowLi stener interface are invoked when the stato
O the window
changes. The object of WindowEvent class is passed as method
parameter.
he general form of the methods defined in WindowListener interface is
void windowopened (WindoWEvent
we
void windowclosed (WindowEvent we)
void windowclosing (WindowEvent we)
void windowactivated (WindowEvent we)
void windowDeactivated (WindowEvent we)
void windowIconified (WindowEvent we)
void windowDeiconified (WindowEvent we)

The PropertyChangeListener Interface


The method defined by the Propert yChangeListener interface is invoked wher
the property ofthe source object changes. The object of PropertyChangeEvent
class is passed as method
parameter.
The general form ofthe method defined in PropertyChangelistene:
interfaceis
void PropertyChange (PropertyChangeEvent pce)

The ChangeListener interface


The method defined by the ChangeListener interface is invoked when the sourc=
object changes. It is used bythe components like scroll bars. The object of ChangeEven-
class is passed as method parameter.
The general form ofmethod defined in ChangeListener interface is
void stateChanged (ChangeEvent ce)

The CaretListener Interface


The method defined by the CaietListener interface is invoked when the positic
of the caret (cursor) changes or when text is selected. The object of cCaretEven
class is passed as method parameter.
The general form ofthe method defined in CaretListener interface is
void caretUpdate (Caret Event ce)
To understand the concept of event handling, consider Example 11.1 and Examp-
11.2. Example 11.1 demonstrates the generation of key events when the user presses.
releases any keyboard key. The methods of the KeyListener interface are invoke
when the key is pressed or released and output is displayed to the user in the status b
of the applet window. Example 11.2 demonstrates the generationofmouse evetswh
the user presses or releases the mouse buttons. The methods ofthe MouseListene
interface are invoked when the mouse js pressed or released and output is displayed
Self-Instructional the user in the status bar of the browser window.
148 Muterial
u. U. u.

oid

(D
Event Handling is
The output of the HTML code

Applet Viewer: ExamplekKeyl istenet class


Applet
NOTES This Is your Key LIstener Class

Check Your Progress


Which of the
following is true? You have pressed the key extends Applet class
class
(a) Java 1.0 model has
method, the applet registers
KeyListenerExample

the
replaced
Delcgation Event
ln this example,
KeyListener
interface. In the
i n i t ()
the applet itself is the
andimplements be noted that here
model. listener for key events. It should the methods defined by
ESelf as a
events. This applet
implements all
(b) The Delegation Sourceand listener for these
Event model use
the KeyListener interface.
event listeners to
the event handling mechanism using
demonstrate
handle events. to
Example 11.2: An applet
(c) Java 1.0 model is MouseListener interface
more efficient than
Delegation Event
import [Link]. *;
model.
import [Link].*;
(d) The Delegation
Event model uses import [Link]. *;
handleEvent ()
method to process
events. /*
width=400 height=400>
What is an even, code="MouseEventHandle"

applet
event source and
event listener? </applet>

The highest class /


in delegation event

model extends Applet implements


public class MouseEventHandle
MouseListener
4. The
ActionEvent is
generated with the
click of a button.
String message=" ";
(True or False) int Xcoordinate=0, Ycoordinate=0;

5. The public void init()

interface defines
methods to handle
events related to
adaMouselistener (this);
keys in Java.

6. What are the


adapter classes? // Mouse clicked event handling
How are adapter public void mouseclicked (MouseBvent me)
classes useful?

Self-Instructional
150 Material
1 saving the
coordinates of mouse
Kcoordinate=0; Event Handling

Ycoordinate=20 ;
message= "Mouse
clicked event";
repaint ();
NOTES

/ Mouse entered
event
public void handling
mouseEntered (MouseEvent me)
1 saving the
coordinates of mouse
Xcoordinate=0;
Ycoordinate=20;
message= "Mouse entered
event";
repaint ()

I Mouse exited event


handling
public void mouseExited (MouseEvent me)

1/ saving the coordinates of mouse


Xcoordinate=0;
Ycoordinate=20;
message= "Mouse exited
event";
repaint();

// Mouse pressed event handling


public void mousePressed (MouseEvent me)

//saving the coordinates of mouse

Xcoordinate=0 ;
Ycoordinate=20;
message= "Mouse pressed event";

repaint ();

// Mouse released event handling


public void mouseReleased (MouseEvent me)

1/ saving the coordinates of mouse


Xcoordinate=0;
Ycoordinate=20;

Self-Instructional
Material 151
Event Handling

nessage= "Mouse released event"i

repaint ():
NOTES
I displaying essage in the applet window at the
/location of x, y coordinates.
current
public void paint (Graphics g

[Link] (message, Xcoordinate=0, Ycordinate=20).

HTML code:
<HTML

HEAD><TITLE>MouseEventHandling«/TITLE> </HEAD>
<BODY>
<CENTER>
APPLET coDE="[Link]" WIDTH=800
HEIGHT=700>
</APPLET>
</CENTER
</BODY>
</HTML>
The output of the HTML code is

Mouset ventHande ling Microsoft Intlernet


Fle E Vew
Explorer
Favares Tools Heb

Mouse Event handeling


Mouse pressed event

Applet MauseEvertHendestated y Computer


In this example, the MouseEventHandle class extends Applet class and
implements MouseListener interface. In the init () method, the applet registers
itself as a listener for mouse events. It should be noted that here the applet itself is the
source and listener for these events. This applet
implements all the methods definedby
the MouseListener interface.

Self-Instructional
152 Material
Event Handling

11.4.4 Adapter Classes


feature in Java, known as adapter class. Adapter class implementsan
There is a special methods inn
and defines all its method with empty body. The
event listener interface in
adapter class
do not provide any additional functionality. Adapter classes
are
used NOTES

only some of the events of particular


a
when programmers need to process
situation an
event listener interface. A new event listener class can be defined by extending
There is an adapter
adapter class and implementing only those events that are required.
of the mostly used adapter
class available for each of the event listener interface. Some
classes are listed in the Table 11.3.
Table I1.3 Adapter Classes and Corresponding Listener Interface

Adapter Class Listenerinterface


WindowAdapter WindowListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
KeyAdapter KeyListener
FocusAdapter FocusListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
MouselnputAdapter MouselInputListener
Example 11.3: An applet to demonstrate the event handling mechanism of mouse
motion using the adapter classes.
import [Link].*;
import [Link]. event.*;
import [Link]. *;

/*
<applet code="AdapterExample" width=300 height=300>
</applet>

public class AdapterExample extends Applet

public void init()

addMouseMotionListener (new MouseMotion (this) ) ;

class MouseMotion extends MouseMotionAdapter

AdapterExample adex;
public MouseMotion (AdapterExample adex)

[Link]=adex;

Self-Instructional
Material 153
Event Handling

move
event
/handle mouse
(MouseEvent me
mouseMoved
public void

moved") i
NOTES [Link] ( "Mouse

HTML code: class


adapter
Mouse motion with
CLASS</TITLEs

<HTML> ADAPTER
MOTION
WITH
ADS<TITLE>MOUSE

</HEAD>

<BODY>
WIDTH=800
<CENTER> A d a p t e r E x a m p l e . c l a s s "

coDE="
CAPPLET

HEIGHT=700>

</APPLET>
</CENTER>

</BODY

</HTML
is
The output of the HTML code

Microsoft Internet Explorer


ROUSE 0TON WIH ADAPTIR
LASS

He Ed Vew Fevortes Toos Hep

Mouse monoa with adapter class

M Computer
Mause noved
extends Applet class. In the
In this example, the AdapterExample class
listener for mouse motion events. It
init() method, the applet registers itself as
a

listener for these events. This


should be noted that here the applet itselfis the source and
class but
appletimplements all the methods defined by the MouseMotionAdapter
we are using only the mous eMoved method in the program.

Self-Instructional
154 Material
11.5 SUMMARY Event Handling
tn this unit, you have learned that:
In Java, all the
activities that occur
termed as events. between the user and the
An event is an
application are NOTES
object which specifies the
generated, whenever an change
action takes place like of state in the source. It is
is modified. a mouse button is clicked or text
Java packages such as
[Link], java. awt and
support event handling mechanism.
The
[Link]
working of an event-driven
handling model. program is governed by its underlying
event
.The Java 1.0 Event model
of containment. of Java for event processing was based on the
concept
.The Delegation Event
Model defines a logical
based on the
concept source and listener. Aapproach
of to handle events. It
is
sends it to one or more listeners source generates an event and
that can handle the
Java provides various classes event
and interfaces to handle the generated events.
.Some of the event classes are
ItemEvent, KeyEvent, ActionEvent, AdjustmentEvent,
etc. WindowEvent, ChangeEvent, CaretEventt
Some of the event listener
interfaces
ActionListener, are
AdjustmentListener, ItemListener, KeyListener,
WindowListener, ChangeListener, CaretListener, etc.
11.6 KEY TERMS
.HTML elements:It indicates to the
HTML document and marks the Web browser that the page loaded is an
beginning and end of the HTML document.
.HEAD element: It specifies the header
infomation about the HTML document
such as title, keywords, and so on.
.Color class: It provides various methods to
use any color wanted to
defining various color constants, which can be directly used by display by
color of choice. specifying the

11.7 ANSWERS TO CHECK YOUR


PROGRESS'
1. B
2. Event: In Java, an event is
represented by an object which specifies the change
of state in the source.
Event Source: An event source is an object that generates a particular kind of
event.
Event Listener: An event listener is an object which receives notification when an
event occurs.
3. EventObject

Self-Instructional
Material 155
Event Handling
4. Truc
5. KeyListener an
cvent ener interfac
listen
inmplements
which
are the classes,
6. Adapter classes are
with blank body. we can define a n cfinc new
NOTES and define all ts method
the code because
7. arehelpful
in reducing and implemcnting only
th those
Adapter classes an adapted class events.
vent listener class by extending all the
implementing
vents that are required
instead of
EXERCISES
11.8 QUESTIONS AND
-

Short-Answer Questions
1. What is an event?
in Java.
for event handling
2. List the models proposed
five cvent
classes.
3. What are event classes? List

Long-Answer Questions
model.
1. Discuss the delegation event event listener.
event source and
2 Explain the meaning ofevent, event handling in Jau
interfaces that support a.
3. List and describe the
classes and

Self-Instructional
156 Material

You might also like