Unit 06
Event Handling
1
Introduction
Event Handling - Introduction
Event handling in Java is the mechanism that controls the
response to user actions like button clicks, mouse
movements, key presses, etc. Java uses the Event
Delegation Model to handle these actions. This model
enables event processing by delegating the task to
listeners.
An event is an object that describes a change in the state
of a source (e.g., a button being clicked).
2
3
4
Components in Event Handling
The following are the three main
components of event handling in Java:
Events
Event Sources
Event Listeners/Handlers
5
Events
The events are defined as an object that describes a change in the state of a
source object. Java defines a number of such Event Classes
inside java.awt.event package.
Some of the events are as follows:
ActionEvent: Occurs when a button is clicked or an action is performed.
MouseEvent: Triggered by mouse actions (click, drag, move).
KeyEvent: Generated when a key is pressed, released, or typed.
FocusEvent: Occurs when a component gains or loses focus.
ItemEvent: Fired when an item is selected/deselected (e.g., checkbox).
6
Event Sources
A source is an object that generates an event. An event
generation occurs when an internal state of that object changes in
some way. A source must register listeners in order for the listeners
to receive notifications about a specific type of event.
Some of the event sources are as follows:
Button: Generates an ActionEvent when clicked.
CheckBox: Generates an ItemEvent on selection change.
List: Fire ActionEvent or ItemEvent on item selection.
Choice: Triggers ItemEvent when an option is chosen.
Window: Shows WindowEvent on close/minimize/maximize.
7
Event Listeners
A listener is an object that is notified when an event occurs. A Listener has two major
requirements: it should be registered to one or more source objects to receive event
notifications, and 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.
Some of the listeners are as follows:
ActionListener: Handles button clicks like actionPerformed().
MouseListener: Handles mouse events like mouseClicked() and mousePressed().
ItemListener: Manages ItemEvent like checkbox and radio button toggles.
KeyListener: Handles keyboard input like keyPressed() and keyReleased().
WindowListener: Handles window operations
like windowOpened() and windowClosed().
8
Event Delegation Model
The Event Delegation Model is a standard design pattern
used in Java:
Source: The component (like a button) that generates the
event.
Listener: An object that wants to be notified when the event
occurs.
The source registers listener(s) and sends the event to them.
Advantages:
Separation of design and behavior
Efficient event handling
9
10
11
12
13
14
15
16
17
ADAPTER CLASSES
An interface holds only abstract methods and its implementation requires all its methods to
be implemented, i.e., overridden with real methods in the implementing class. This is true
for listener interfaces also; if you are implementing a particular listener interface, you have
to implement all the methods defined in that interface. This can really be annoying at
times, where you must also implement all those methods of the listener interface, which
might not actually be used. In order to simplify things, Java came up with the concept of
adapter classes. For listener interfaces containing more than one event handling methods,
JDK defines corresponding adapter classes.
MouseMotionListener interface. So how would the MouseMotionListener interface be
defined by Java? As we know, this interface has two methods defined as follows:
public interface MouseMotionListener
{
public void mouseDragged (MouseEvent e);
public void mouseMoved (MouseEvent e);
}
18
The corresponding adapter class, i.e., MouseMotionAdapter is
predefined in Java as follows:
public class MouseMotionAdapter implements MouseMotionListener
{
public void mouseDragged (MouseEvent e) { }
public void mouseMoved (MouseEvent e) { }
}
19
Inner Classes in Event Handling In Java event handling, inner classes are useful for
writing event listener code close to the GUI component it handles.
They help organize code better and increase readability and maintainability.
Types of Inner Classes:
Member Classes
Defined like fields/methods inside a class.
Can be:
Static Member Class – Accesses only static members of the outer class.
Instance Member Class – Accesses both static and instance members of the
outer class.
Local Classes
Defined inside a method or a block.
Exist only while the method is executing.
Anonymous Classes
No name, defined and instantiated in a single expression.
Commonly used in event handling for short, one-time use listeners.
20
INTRODUCTION The Abstract Window Toolkit (AWT) provides many
classes—which can even be used inside applets—for programmers to
use. It is the connection between your application and the native GUI.
The AWT hides the complexities of the GUI your application will be
running on. The Java foundation classes (JFC) provide two frameworks
for building GUI-based application and interestingly both rely on the
same event handling model:
AWT
Swing AWT relies on the underlying operating system on a specific
platform to represent its GUI components (i.e., components in AWT are
called heavyweight), while swing implements a new set of lightweight
GUI components that are written in Java and has a pluggable look and
feel. These lightweight components are not dependent on the
underlying window system. In this chapter, we will put emphasis on
AWT, while swings will be covered in the next chapter. AWT API can be
used in any Java program by importing the java.awt.* package.
21
java.awt Package The package java.awt contains all classes used
for creating graphical user interfaces, painting graphics, images,
colors, and fonts. A user interface element such as a button or a
textbox is called a component. The Component class is the
superclass of all AWT components. These components fi re events
when users interact with these components, e.g., when a user clicks
on a button. These events are handled by event handling classes,
i.e., AWTEvent and its subclasses.
22
23
COMPONENTS AND CONTAINERS
A graphical user interface is developed with the help of graphical elements such
as buttons, scrollbars, lists, and textfields.
These elements are called components. These components are generally the
source of events that allow the user to interact with the program (remember, the
event handling mechanism).
In AWT, these components are instances of the respective Component classes.
Components cannot exist alone; they are found within containers. The layout of
the components are contained and controlled within the containers.
In fact, containers are themselves components, thus they can be placed inside
other containers. In AWT, all containers are objects of class Container or one of
its subtypes.
24
Hierarchy of Classes in AWT
25
BUTTON
Button() throws HeadlessException
Button(String str)throws HeadLessException;
The first constructor, when called, creates a Button with no label displayed on it. The second constructor creates a Button,
displaying the string ‘str’ on it. Now, how is a Button actually created? See the syntax below,
Button buttonName = new Button(Str);
where buttonname is the name of the button object and str is the text which you want to set as the caption of the button.
Once the object for Button is created, it needs to be added to the applet, frame or any other container. The syntax for it is
as follows:
add(buttonname);
The methods like setLabel() and getLabel() are used for changing the button’s label and getting the label’s text
respectively. The signatures of these methods are
void setLabel(String str)
String getLabel()
26
27
CHECKBOX Checkboxes are used as on-off or yes-no switches
since every time you click on one, you toggle to the opposite
selection, i.e., if you click on an unchecked checkbox, it will get
checked and if you click on the checked box, it will get unchecked.
You can check as many checkboxes as you wish to, as there is no
constraint on selecting the number of checkboxes.
Your program can be made to respond as per the state of each
checkbox. An element-like button might be needed to trigger an
event to check the state of the checkboxes. The checkboxes are the
objects of Checkbox class, which support the following constructors:
Checkbox()
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, CheckBoxGroup cbg, boolean on)
28