0% found this document useful (0 votes)
22 views

II Event-Handling

Uploaded by

Umera Rawoot
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)
22 views

II Event-Handling

Uploaded by

Umera Rawoot
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
You are on page 1/ 35

Event Handling

Introduction to Event Handling


• In Java GUI applications, a user's interaction with a component is
called an event. As a programmer, you can write code to do
something after these events. This is why Java is referred to as
being event driven. In Java, the general term for an event is
the event object.
• In computer programming, event-driven programming is a programming
paradigm in which the flow of the program is determined by events such as
user actions (mouse clicks, key presses), sensor outputs, or messages from
other programs or threads.
• Event-driven programming is the dominant paradigm used in graphical user
interfaces and other applications (e.g., JavaScript web applications) that
are centered on performing certain actions in response to user input. This
is also true of programming for device drivers
• In an event-driven application, there is generally a main loop that listens
for events and then triggers a callback function when one of those events is
detected. In embedded systems, the same may be achieved
using hardware interrupts instead of a constantly running main loop. Event-
driven programs can be written in any programming language, although
the task is easier in languages that provide high-level abstractions, such
as await and closures.
Basic "styles" of program
1. Non-interactive programs: No interaction with a user while program is
running.
2. Interactive programs: Dialogue with a user, with program “in the driver's
seat” Though once common, pure examples of this sort of program are
becoming increasingly rare.
3. Responsive, or event-driven programs: Program consists of a set of
“handlers” for various events (e.g. mouse click on a button, menu choice).
The user is “in the driver's seat”. Examples: Most GUI programs are of this
sort - e.g. a word processor. Many embedded systems - e.g. software on a
microwave oven responds to events like user pressing a button, user
opening/closing door, timer “ticking”. There may also be a method for
initially setting things up.
BASIC program, Procedural model
• In a BASIC program, the general program flow was that it would "start
at the beginning and work through to the end", possibly with a few
subroutine calls along the way. This is a nice, easy-to-understand
model for simple applications. But with today's complex, windowed,
multi-tasking operating systems, the procedural model doesn't often
work very well.
Event-driven model

• Instead, Java (and programming for modern operating systems in


general) takes an event-driven approach. In a typical windowed
application, the program sets up event handlers: pieces of code to
run when something interesting happens, such as mouse click inside
one of the application's windows. For much of the rest of the time,
none of your code may actually be running.
Multithreading…

• Another important notion in Java programming (and again, in modern


programming in general), is the notion of threads: sub-strands of a
program that can run in parallel. A main program might spawn
threads to perform particular jobs in the background, or break a
calculation into several parts that run simultaneously. Modern
computers are typically designed to allow several threads to physically
run in parallel, and beyond this the operating system can make
different threads effectively run in parallel by "swapping them in and
out" of the processor.
What is an Event?

• Change in the state of an object is known as Event, i.e., event describes


the change in the state of the source. Events are generated as a result of
user interaction with the graphical user interface components. For
example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from the list, and scrolling the page
are the activities that causes an event to occur.
Vocabulary
• Event: an action that causes something to happen.
• Event-driven program: a program designed to run blocks of code or
functions in response to specified events (e.g. a mouse click)
• Event handling: an overarching term for the coding tasks involved in
making a program respond to events by triggering actions.
• Event listener: a command that can be set up to trigger an action when a
particular type of event occurs on a particular UI element.
• Callback function: a function specified as part of an event listener; it is
written by the programmer but called by the system as the result of an
event trigger.
• User Interface (UI): the visual elements of a program through which a user
controls or communicates with the application. Often abbreviated UI.
• UI Elements: on-screen objects, like buttons, images, text boxes, pull-down
menus, screens and so on
Types of Event
• The events can be broadly classified into two categories −
• Foreground Events − These events require direct interaction of the
user. They are generated as consequences of a person interacting
with the graphical components in the Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the
page, etc.
• Background Events − These events does not require the interaction of
the end user. Operating system interrupts, hardware or software
failure, timer expiration, and operation completion are some
examples of background events.
What is Event Handling?
• Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism has a code which is
known as an event handler, that is executed when an event occurs.
• Java uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
• The Delegation Event Model has the following key participants.
• Source − The source is an object on which the event occurs. Source is
responsible for providing information of the occurred event to it's handler.
Java provide us with classes for the source object.
• Listener − It is also known as event handler. The listener is responsible for
generating a response to an event. From the point of view of Java
implementation, the listener is also an object. The listener waits till it
receives an event. Once the event is received, the listener processes the
event and then returns.
Two Event Handling Mechanisms in Java
1. Original Version of Java (1.0)
2. Modern Versions of Java, beginning with Java version 1.1
• The way during which events are handled changed significantly
between the first version of Java (1.0) and every one subsequent
version of Java, beginning with version 1.1. Although the 1.0 method
of event handling remains supported, it’s not recommended for
brand spanking new programs.
• Also, many of the methods that support the old 1.0 event model are
deprecated. The modern approach is the way that events should be
handled by all-new programs.
Delegation Event Model
• We know about Source, Listener, and Event. Delegation event model
joins these 3 entities and make them work in sync. The modern
approach to handling events is predicated on the delegation event
model, which defines standard and consistent mechanisms to get and
process events. Its concept is sort of simple: a source generates an
occasion and sends it to at least one or more listeners. In this scheme,
the listener simply waits until it receives an occasion. Once an
occasion is received, the listener processes the event and then
returns.
Delegation Event Model…
Delegation Event Model…
• Using the delegation event model is actually quite easy. Just follow
these two steps:
• Implement the appropriate interface in the listener so that it will
receive the type of event desired.
• Implement code to register and unregister (if necessary) the listener
as a recipient for the event notifications.
Advantages of using the Delegation Event Model
• The advantage of this design is that the appliance logic that processes
events is cleanly separated from the interface logic that generates
those events. An interface element is in a position to “delegate” the
processing of an occasion to a separate piece of code. In the
delegation event model, listeners must register with a source so as to
receive an occasional notification. This provides is a crucial benefit:
notifications are sent only to listeners that want to receive them. This
is a more efficient way to handle events.
• Note: Java also allows you to process events without using the
delegation event model. This can be done by extending an AWT
component.
Steps Involved in Event Handling
• Step 1 − The user clicks the button and the event is generated.
• Step 2 − The object of concerned event class is created automatically and
information about the source and the event get populated within the same
object.
• Step 3 − Event object is forwarded to the method of the registered listener
class.
• Step 4 − The method gets executed and returns.
• Points to Remember About the Listener:
• In order to design a listener class, you have to develop some listener interfaces.
These Listener interfaces forecast some public abstract callback methods, which
must be implemented by the listener class.
• If you do not implement any of the predefined interfaces, then your class cannot act
as a listener class for a source object.
Components of Event Handling
1. Events:
An event is an object that describes a phase change during a
source. It is often generated as a consequence of an individual
interacting with the weather during a graphical interface. Some
activities that cause events to be generated are pressing a button,
entering a personality via the keyboard, selecting an item during a list,
and clicking the mouse. Events can also occur that aren’t directly
caused by interactions with an interface. For example, an occasion
could also be generated when a timer expires, a counter exceeds a
worth, a software or hardware failure occurs, or an operation is
completed.
Components of Event Handling…
2. Event Sources:
A source is an object that generates an occasion. This occurs
when the interior state of that object changes in how. Sources may
generate quite one sort of event. A source must register listeners so as
for the listeners to receive notifications a few specific sorts of events.
Each sort of event has its own registration method. Here is the general
form:
public void addTypeListener(TypeListener el)
Here, the Type is the name of the event and el may be a regard to the
event listener.
Components of Event Handling…
• 3. Event Listeners in Java:
A listener is an object that’s notified when an occasion occurs. It
has two major requirements. First, it registered with one or more
sources to receive notifications about specific sorts of events. Second,
it implements methods to receive and process these notifications. The
methods that receive and process events are defined in interfaces
found in java.awt.event.
Event Listeners in Java…
Event Classes
• The classes that represent events are at the core of Java’s event
handling mechanism. At the root of the Java event, the class hierarchy
is EventObject, which is in java.util. It is the superclass for all events.
Callback Methods
• These are the methods that are provided by API provider and are
defined by the application programmer and invoked by the
application developer. Here the callback methods represent an event
method. In response to an event, java JRE will fire callback method.
All such callback methods are provided in listener interfaces.
• If a component wants some listener to listen to its events, the source
must register itself to the listener.
Common GUI Event types and Listener
Interfaces
Information about the event that occurs when the user presses Enter in a
text field is stored in an ActionEvent object. There are many different types
of events that can occur when the user interacts with a GUI. The information
about any GUI event that occurs is stored in an object of a class that
extends AWTEvent. Following figure illustrates a hierarchy containing many
event classes from the package java.awt.event. These event types are
used with both AWT and Swing components. Additional event types that are
specific to Swing GUI components are declared in
package javax.swing.event.
Some event classes of package java.awt.event
Summarize: The event-handling mechanism
• The event source is the particular GUI component with which the user
interacts.
• The event object encapsulates information about the event that occurred,
such as a reference to the event source and any event-specific information
that may be required by the event listener for it to handle the event.
• The event listener is an object that is notified by the event source when an
event occurs; in effect, it "listens" for an event and one of its methods
executes in response to the event. A method of the event listener receives
an event object when the event listener is notified of the event. The event
listener then uses the event object to respond to the event. The event-
handling model described here is known as the delegation event model an
event's processing is delegated to a particular object (the event listener) in
the application.
Summarize…
• For each event-object type, there is typically a corresponding event-
listener interface. An event listener for a GUI event is an object of a
class that implements one or more of the event-listener interfaces from
packages java.awt.event and javax.swing.event. Many of the event-
listener types are common to both Swing and AWT components. Such
types are declared in package java.awt.event, and some of them are
shown in following Fig. Additional event-listener types that are
specific to Swing components are declared in package
javax.swing.event.
Some common event-listener interfaces of
package java.awt.event
• Figure next page

• Each event-listener interface specifies one or more event-handling methods that


must be declared in the class that implements the interface. Recall from that any
class which implements an interface must declare all the abstract methods of that
interface; otherwise, the class is an abstract class and cannot be used to create
objects.

• When an event occurs, the GUI component with which the user interacted
notifies its registered listeners by calling each listener's appropriate event-
handling method. For example, when the user presses the Enter key in a
JTextField, the registered listener's actionPerformed method is called. How did
the event handler get registered? How does the GUI component know to call
actionPerformed rather than another event-handling method? We answer these
questions and diagram the interaction in the next section
How event handling works
• Let us illustrate how the event-handling mechanism works, using
textField1 from the example. We have two remaining open questions
from :

• How did the event handler get registered?


• How does the GUI component know to call actionPerformed rather
than some other event-handling method?
• The first question is answered by the event registration performed by
JTextField variable textField1, TextFieldHandler variable handler
and the objects to which they refer.
Event registration for JTextField textField1

textField1 handler

JTextField object TextFieldHandler object


public void actionPerformed (
listenerList ActionEvent event )
{
//event handled here
}

This reference is created by the statement


textField1.addActionListener( handler );
Registering Events
• Every JComponent has an instance variable called listenerList that refers to
an object of class EventListenerList (package javax.swing.event). Each
object of a JComponent subclass maintains a references to all its registered
listeners in the listenerList. For simplicity, we have diagramed listenerList as
an array below the JTextField object in Fig. on previous page

• When code “textField1.addActionListener( handler );” (In our program,


b1.addActionListener(this)) executes, a new entry containing a reference
to the TextFieldHandler object is placed in textField1's listenerList.
Although not shown in the diagram, this new entry also includes the
listener's type (in this case, ActionListener). Using this mechanism, each
lightweight Swing GUI component maintains its own list of listeners that
were registered to handle the component's events.
Event-Handler Invocation
• The event-listener type is important in answering the second question:
How does the GUI component know to call actionPerformed rather than
another method? Every GUI component supports several event types,
including mouse events, key events and others. When an event occurs, the
event is dispatched to only the event listeners of the appropriate type.
Dispatching is simply the process by which the GUI component calls an
event-handling method on each of its listeners that are registered for the
particular event type that occurred.
• Each event type has one or more corresponding event-listener interfaces.
For example, ActionEvents are handled by ActionListeners, MouseEvents
are handled by MouseListeners and MouseMotionListeners, and KeyEvents
are handled by KeyListeners.
Event-Handler Invocation…
• When an event occurs, the GUI component receives (from the JVM) a
unique event ID specifying the event type. The GUI component uses
the event ID to decide the listener type to which the event should be
dispatched and to decide which method to call on each listener
object. For an ActionEvent, the event is dispatched to every registered
ActionListener's actionPerformed method (the only method in
interface ActionListener). For a MouseEvent, the event is dispatched
to every registered MouseListener or MouseMotionListener,
depending on the mouse event that occurs. The MouseEvent's event
ID determines which of the several mouse event-handling methods
are called.
Event-Handler Invocation…
• All these decisions are handled for you by the GUI components. All
you need to do is register an event handler for the particular event
type that your application requires and the GUI component will
ensure that the event handler's appropriate method gets called when
the event occurs.
• [Note: We discuss other event types and event-listener interfaces as they
are needed with each new component we introduce.]

You might also like