This document provides an overview of event handling in Advanced Java Programming. It discusses the delegation event model, where a source generates an event and a listener receives the event. It describes different types of events like mouse, keyboard, window events and the classes that represent them. It also covers event listener interfaces that must be implemented by listeners to receive and process events from sources. Key concepts covered are event sources, event objects, event listeners, and the delegation model of separating source and listener logic.
4. Unit Outcomes
Use delegation event model to develop event driven program for the given
problem
Use relevant AWT/Swing component to handle the given event
Use adapter classes in java program to solve the given problem
Use inner classes in java program to solve the given problem
5. Introduction to Events
Events are an important part of applet programming
Applets are controlled by events
Events are generated by variety of sources such as :
user keyboard mouse
6. Introduction to Events
Events are generated by variety of sources such as :
Various controls
buttons
checkbox
choice
list
textfield
textarea
etc.
For handling events java.awt.event package is used
7. Delegation Event Model
Delegation event model is a modern approach for handling events
In this model there is a source, which generates event and there is listener which
receives the event from the source
The listener waits for the event and process the event when it is recieved
This seperates the logic of user interface and application logic that processes the
event
In this model, the listener must register with source for receiving event
notification
Due to this only that listener receives event which want to receive and process it
8. What is Event ?
In delegation event model, an event is an object which
contains all the information about change of state of
source of event
Events are generated when user interacts with
graphical user interface (GUI )
It is also generated when user presses button, or
key on keyboard or selects option from list, choice,
checkbox etc.
There are also other indirect sources of events,
which are not caused by interaction of user with
graphical user interface (GUI)
Fig: GUI
9. Other indirect sources of events are as follow :
What is Event ?
timer: when
time expires
counter : when count
reaches a value
software : when
software failure occurs
hardware : when hardware failure occurs
10. In java, source of an event is an object which generates an event
What is Event ?
When state of source of an object changes it generates an event
Source can generate more than one type of event
A source should register the listeners, so that the listener can get notification of
event
The general form of registration for an event is written as :
public void addTypeListener(TypeListener el)
Where, Type = name of event
el = reference to event listener
11. For example, if we want to register listener for keyboard event then we can write
as - addKeyListener( ),
Similarly, for registering listener for mouse motion, we can write as -
addMouseMotionListener( )
What is Event ?
When all registered listeners are notified and receives copy of event object it is
called as multicasting
Some sources of events allows only one listener to register, the general form of
such methods is as below :
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
When only one listener is notified of event it is called as unicasting
12. What is Event ?
Source of an event is also provides a method for removing or unregistering listener,
the syntax of the method is given as below:
public void removeTypeListener(TypeListener el)
For example, the method for removing or unregistering keyboard listener is
written as :
removeKeyListener( );
Component class provides methods (functions) to add and remove keyboard and
mouse event listeners
13. Event Listeners
Listeners are objects that receives notification when an event occurs
A listener must be register with one or more source to receive notification of an
event
It should have methods (functions) to receive and process the event notification
Methods that receive and process events are defined (found) in a group of
interfaces in java.awt.event package
14. Event Classes
In java there are classes that represents events, such classes are called as Event
classes
EventObject class is a root class of java's event class heirarchy
EventObject class is present in java.util package
It is super class (top most class) for all types of events
Constructor EventObject(Object src), where src = object that generates the event
Methods (functions) of EvenObject class :
getSource( ) - returns source of event
toString( ) - returns string description of event
15. Event Classes
The AWTEvent class is superclass (top most class) of all AWT-based events used by
delegation event model
The AWTEvent class is present in java.awt package, it is subclass (child class) of
EventObject class
int getID( ) - tells type of event
java.awt.event package describes several types of events
18. ActionEvent Class
ActionEvent is created when - button is pressed, list item is double clicked or menu
item is selected
ActionEvent has four integer constants :
ALT_MASK = whether ALT key was pressed
CTRL_MASK = whether CTRL key was pressed
META_MASK = whether META key was pressed
SHIFT_MASK = whether SHIFT key was pressed
ActionEvent class has three constructors :
ActionEvent(Object src,int type,String cmd)
, ActionEvent( Object src,int type,String cmd,int modifiers)
ActionEvent( Object src,int type,String cmd, long when, int modifiers)
19. ActionEvent Class
Where :
src = reference to object that generated the event
type = what type of event is
cmd = command string of event
modifier keys = ALT,CTRL,META or SHIFT keys were pressed or not
when = when the event has occured
String getActionCommand( ) - returns command name of event object
int getModifiers( ) - returns which modifier key was pressed when event occured
int getWhen( ) - returns the time when event occurs (timestamp)
20. AdjustmentEvent Class
AdjustmentEvent is created by scroll bar
Five types of AdjustmentEvent are as follows :
BLOCK_DECREMENT = when user clicks inside scroll bar to decrease its value
BLOCK_INCREMENT = when user clicks inside scroll bar to increase its value
TRACK = when the slider is dragged
UNIT_DECREMENT = when button at the end of scroll bar is clicked to decrease
it's value
UNIT_INCREMENT = when button at the end of scroll bar is clicked to increase it's
value
21. AdjustmentEvent Class
ADJUSTMENT_VALUE_CHANGED - tells whether change has occured or not
AdjustmentEvent class has one constructor :
AdjustmentEvent(Adjustable src, int id, int type, int data)
Where src = reference to the object that generated the event
id = ADJUSTMENT_VALUE_CHANGED
type = type of event
data = data related to the event
Adjustable getAdjustable( ) - returns the object that generates the event
int getAdjustmentType( ) - returns the type of adjusment events from five types of
events
int getValue( ) - returns how much scroll bar is changed
22. ComponentEvent Class
ComponentEvent is created when the size, position,or visibility of component is
changed
Four types of ComponentEvent indentified by integer constants are as follows :
COMPONENT_HIDDEN = the component was hidden
COMPONENT_MOVED = the component was moved
COMPONENT_RESIZED = the component was resized
COMPONENT_SHOWN= the component becomes visible
23. ComponentEvent Class
ComponentEvent class constructor :
ComponentEvent(Component src, int type)
ComponentEvent class is superclass (parent class) of ContainerEvent class,
FocusEvent class, KeyEvent class, MouseEvent class ans WindowEvent class
Component getComponent( ) - returns the component that generated the event
24. ContainerEvent Class
ContainerEvent is created when a component is added to or removed from a
container
Two types of ContainerEvent identified by integer constant are as follow :
COMPONENT_ADDED = when component is added to the container
COMPONENT_REMOVED = when component is removed from the container
ContainerEvent class is subclass(child class) of ComponentEvent class
ContainerEvent(Component src, int type, Component comp)
src = reference to container that generated the event
comp = component that is added or removed from the container
type = type of event
25. ContainerEvent Class
Container getContainer( ) - returns reference to the container that generated this
event
Component getChild( ) - returns reference to the component that was added to or
removed from the container
26. FocusEvent Class
FocusEvent is created when a component gets or loses input focus
Three constructors of FocusEvent class are as follow :
FocusEvent class is subclass(child class) of ComponentEvent class
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
Where src = reference to component that generated the event
type = type of event
27. FocusEvent Class
temoraryFlag has value true or false
temoraryFlag has value true if the focus event is temporary otherwise false
Suppose our focus is in a text field and move the mouse to adjust scroll bar then
we called the focus is temporary lost
the other component is a opposite component when focus changes
When the event type is FOCUS_GAINED, the other component is that component
which lost focus
Similarly, when the event type is FOCUS_LOST, the other component is that
component which gains focus
28. FocusEvent Class
Two types of Focus Event identified by integer constant are as follow :
FOCUS_GAINED = when the component gains the input focus
FOCUS_LOST = when the component loses the input focus
Component getOppositeComponent( ) - this method returns the opposite
component that got or lost the input focus
boolean isTemporary( ) - this method returns whether the focus change is
temporary or not, true means focus change is temporary
29. ItemEvent Class
An ItemEvent is created when - checkbox or list item is clicked, when checkable
menu item is selected or deselected
DESELECTED - when an item is deselected by the user
Two types of ItemEvent identified by integer constant are as follow :
SELECTED - when an item is selected by the user
ITEM_STATE_CHANGED - this constant tells whether the state is changed or not
ItemEvent( ItemSelectable src, int type, Object entry, int state)
where src = the component that generated this event
type = type of event
30. ItemEvent Class
Where entry = item of checkbox or list or checkable menu item that generated the
event
state = the current state of the item
Object getItem( ) - this method returns reference to the item that generated the
event
ItemSelectable getItemSelectable( ) - this method returns reference to the
itemSelectable object that generated the event
List and Choice implements (inherits) ItemSelectable interface
int getStateChange( ) - this method returns the changed state for an event
31. KeyEvent Class
KeyEvent is created when we give input from keyboard
KeyEvent class is a subclass (child class) of InputEvent class
Three types of KeyEvent identified by integer constant are as follow :
KEY_PRESSED - when a key is pressed
KEY_RELEASED - when a key is released
KEY_TYPED - when a character is generated by typing a key
There are some keys which when pressed do not generate character, like SHIFT
key
32. KeyEvent Class
KeyEvent class has various integer constants which are as follow :
VK_0 to VK_9 = ASCII value of numbers
VK_A to VK_Z = ASCII value of letters
Other integer constants are as follow :
VK_ENTER
VK_DOWN
VK_PAGE_UP
VK_ESCAPE
VK_LEFT
VK_SHIFT
VK_CANCEL
VK_RIGHT
VK_ALT
VK_UP
VK_PAGE_DOWN
VK_CONTROL
VK constants means virtual key codes
33. KeyEvent Class
Constructors of KeyEvent class are as follow :
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Where src = reference to component that generated the event
type = type of event
modifiers = which modifier key pressed (control,shift,alt) when key event occured
code = VK_UP or VK_A code is passed here
ch = character equivalent is passed here, if not present then CHAR_UNDEFINED is
passed here
when= system time when KeyEvent occured
34. char getKeyChar( ) - returns the character that was entered, if valid character is
available then it returns CHAR_UNDEFINED,
int getKeyCode( ) - returns key code,when KEY_TYPED event occurs it returns
VK_UNDEFINED
KeyEvent Class
35. MouseEvent Class
MouseEvent is created when we interact with mouse
Eight types of MouseEvent identified by integer constant are as follow :
MOUSE_CLICKED = when the mouse is clicked by the user
MOUSE_DRAGGED = when the mouse is dragged by the user
MOUSE_ENTERED = when mouse enters a component
MOUSE_EXITED = when mouse exits a component
MOUSE_MOVED = when the mouse is moved
MOUSE_PRESSED = when the mouse is pressed
MOUSE_RELEASED = when the mouse is released
MOUSE_WHEEL = when the mouse wheel is moved
36. MouseEvent Class
MouseEvent class is subclass (child class) of InputEvent class
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks, boolean triggersPopup)
Where src = reference to component that generated the event
type = type of event
when= system time when MouseEvent occured
modifiers = which modifier key pressed (control,shift,alt) when mouse event
occured
x, y = x and y coordinates of mouse position
triggersPopup = whether pop up menu appears in this mouse event
37. MouseEvent Class
int getX( ) - returns x coordinate of mouse position when event occured
int getY( ) - returns y coordinate of mouse position when event occured
Point getPoint( ) - returns Point object containing x and y coordinates of mouse
void translatePoint(int x, int y) - changes the location of mouse event by adding x
and y to the old coordinates of mouse event
int getClickCount( ) - number of times mouse is clicked in this event
boolean inPopupTrigger( ) - whether this mouse event causes popup menu to
appear
int getButton( ) - returns a value that tells which button caused the event, the
value can be constants like - NOBUTTON, BUTTON1, BUTTON2, BUTTON3
38. MouseWheelEvent Class
MouseWheelEvent is created when we interact with mouse wheel
MouseWheelEvent class is subclass (child class) of MouseEvent class
Two types of MouseWheelEvent identified by integer constant are as follow :
WHEEL_BLOCK_SCROLL= when page-up or page-down scroll event occurs
Mouse wheels are used for scrolling
WHEEL_UNIT_SCROLL= when line-up or line-down scroll event occurs
MouseWheelEvent( Component src, int type, long when, int modifiers, intx, int y,
int clicks, boolean triggrtPopup, int scrollHow, int amount, int count)
39. MouseWheelEvent Class
Where src = reference to component that generated the event
type = type of event
when= system time when MouseEvent occured
modifiers = which modifier key pressed (control,shift,alt) when mouse event
occured
x, y = x and y coordinates of mouse position
triggersPopup = whether pop up menu appears in this mouse event
scrollHow = constants WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL
amounts = number of units to scroll
count = number of rotations the wheel of mouse has done
40. MouseWheelEvent Class
int getWheelRotation( ) - returns the number of rotations the mouse wheel has
done
int getScrollTypes( ) - returns typeof scroll whether WHEEL_UNIT_SCROLL type or
WHEEL_BLOCK_SCROLL type
int getScrollAmount( ) - if scoll type is WHEEL_UNIT_SCROLL, then this function
returns the number of units to scroll
41. TextEvent Class
TextEvents are created when user or program enters some characters in text
fields or text areas
TextEvent class has a one integer constant TEXT_VALUE_CHANGED
TextEvent class has one constructor which is as follow :
TextEvent( Object src, int type)
Where src = reference to object that generated the event
type = type of event
42. WindowEvent Class
WindowEvents are created when we interact with windows
WINDOW_ACTIVATED = when window is activated
Ten types of WindowEvent identified by integer constant are as follow :
WINDOW_CLOSED = when window is closed
WINDOW_CLOSING = when user requests to close the window
WINDOW_DEACTIVATED = when the window is deactivated
WINDOW_DEICONIFIED = when the window is deiconified
WINDOW_LOS_FOCUS = when the window loses the input focus
WINDOW_LOS_OPENED = when the window is opened
WINDOW_STATE_CHANGED = when the state of window is changed
43. WindowEvent Class
WindowEvents class is subclass (child class) of ComponentEvent class
WindowEvent( Window src, int type)
The constructors of WindowEvent class are as follow :
WindowEvent( Window src, int type, Window other)
WindowEvent( Window src, int type, int fromstate, int tostate)
WindowEvent( Window src, int type, Window other, int fromstate, int tostate
Where src = reference to object that generated the event
type = type of event
other = opposite window when focus event occurs
44. WindowEvent Class
fromstate = previous state of window
tostate = new state of window, when window changes its state
Window getWindow( ) - returns Window object that generated the event
Window getOppositeWindow( ) - returns opposite window when focus event occurs
int getOldState( ) - returns the previous state (old state) of window
int getNewState( ) - returns the new state of window
45. Event Listener Interfaces
Delegation
Event Model
Listener
Interfaces
sources and listeners are two
parts of delegation event model of
event handling
Listeners are created by
implementing (inheriting) one or
more interfaces
Listener interfaces are present in
java.awt.event package
When event occurs,event source
calls method in the listener
interface
Event source also passes an
event object to listener interface
Listener interfaces contain many
methods to handle the events
46. List of Event Listener Interfaces
ActionListener
List of Interfaces
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
MouseWheelListener
TextListener
WindowFocusListener
WindowListener
47. ActionListener Interface
ActionListener interface has one method for processing (handling) the event
void actionPerformed(ActionEvent ae) - this method is called (invoked) when
action event occurs
Where ae = object of ActionEvent class is passed to method
48. AdjustmentListener Interface
AdjustmentListener interface has one method for processing (handling) the event
void adjusmentValueChanged(AdjustmentEvent ae) - this method is called
(invoked) when adjustment event occurs
Where ae = object of AdjustmentEvent class is passed to the method
49. ComponentListener Interface
ComponentListener interface has four methods for processing (handling) the
event
void componentResized(ComponentEvent ce) - this method is called (used) when
component is resized
Where ce = object of ComponentEvent class is passed to the method
void componentMoved(ComponentEvent ce) - this method is called (used) when
component is moved
void componentShown(ComponentEvent ce) - this method is called (used) when
component is shown or visible
void componentHidden(ComponentEvent ce) - this method is called (used) when
component is hidden or not visible
50. ContainerListener Interface
ContainerListener interface has two methods for processing (handling) the event
Where ce = object of ContainerEvent class is passed to the method
void componentAdded(ContainerEvent ce) - this method is called (used) when a
component is added to the container
void componentRemoved(ContainerEvent ce) - this method is called (used) when a
component is removed from the container
51. FocusListener Interface
FocusListener interface has two methods for processing (handling) the event
Where fe = object of FocusEvent class is passed to the method
void focusGained(FocusEvent fe) - this method is called (used) when a component
gets keyboard focus
void focusLost(FocusEvent fe) - this method is called (used) when a component
loses keyboard focus
52. ItemListener Interface
ItemListener interface has one methods for processing (handling) the event
Where ie = object of ItemEvent class is passed to the method
void itemStateChanged(ItemEvent ie) - this method is called (used) when state of
the item changes
53. KeyListener Interface
KeyListener interface has three methods for processing (handling) the event
Where ke = object of KeyEvent class is passed to the method
void keyPressed(KeyEvent ke) - this method is called (used) when key is pressed
void keyReleased(KeyEvent ke) - this method is called (used) when key is released
void keyTyped(KeyEvent ke) - this method is called (used) when we type any
character (apbhabets, numbers, symbols etc.) from the keyboard
When we press a character key like 'B' key then three key events are generatedin
sequence they are - key pressed, key typed and key released events
Similarly when we press a non-character key like 'SHIFT' key then two key events
are generated in sequence they are - key pressed and key released events
54. MouseListener Interface
MouseListener interface has five methods for processing (handling) the event
void mouseClicked(MouseEvent me) - this method is called (used) when mouse is
pressed and released immediately i.e clicked
void mouseEntered(MouseEvent me) - this method is called (used) when mouse
enters a component like textfield, button etc.
void mouseExited(MouseEvent me) - this method is called (used) when mouse
moves away from a component like textfield, button etc.
55. void mousePressed(MouseEvent me) - this method is called (used) when mouse is
pressed
void mouseReleased(MouseEvent me) - this method is called (used) when mouse is
released
MouseListener Interface
Where me = object of MouseEvent class is passed to the method
mouse is clicked
56. void mouseMoved(MouseEvent me) - this method is called many times when the
mouse is moved
void mouseDragged(MouseEvent me) - this method is called many times when the
mouse is dragged
MouseMotionListener interface has two methods for processing (handling) the
event
MouseMotionListener Interface
Where me = object of MouseEvent class is passed to the method
mouse is moved or
dragged
57. void mouseWheelMoved(MouseWheelEvent mwe) - thi method is called (used)
when mouse wheel is moved
MouseWheelListener interface has one method for processing (handling) the
event
MouseWheelListener Interface
Where mwe = object of MouseWheelEvent class is passed to the method
mouse wheel is
moved
58. void textChanged(TextEvent te) - this method is called (used) when there is change
in textfield or text area
TextListener interface has one method for processing (handling) the event
TextListener Interface
Where te = object of TextEvent class is passed to the method
59. void windowGainedFocus(WindowEvent we) - this method is called (used) when
window gets input focus
WindowFocusListener interface has two methods for processing (handling) the
event
WindowFocusListener Interface
Where we = object of WindowEvent class is passed to the method
void windowLostFocus(WindowEvent we) - this method is called (used) when
window losses input focus
60. void windowActivated(WindowEvent we) - this method is called (used) when
window is activated that is when window comes foreground or when it first
appears
WindowListener interface has seven methods for processing (handling) the event
WindowListener Interface
void windowClosed(WindowEvent we) - this method is called (used) when window
is closed
void windowClosing(WindowEvent we) - this method is called (used) when window
is closing
void windowDeactivated(WindowEvent we) - this method is called (used) when
window is deactivated that is window moves to background
61. WindowListener Interface
void windowIconified(WindowEvent we) - this method is called (used) when
window is changed from normal state to minimize state, minimized window is
displayed as icon
void windowOpened(WindowEvent we) - this method is called (used) when
window is shown for the first time
void deiconified(WindowEvent we) - this method is called (used) when window is
changed from minimize state to normal state
62. Delegation Event Model - How to develop event handling programs ?
Create GUI components like button,texfield,list,checkbox,label etc.
Register components for event listeners (addActionListener for
buttons, addMouseListener for mouse events etc.)
Inherit appropriate Listener interface for matching events (
TextListener for TextEvents, ItemListener for ItemEvent etc.)
Implement methods of Listener interface for event processing
(actionPerformed() method of ActionListener etc.
Steps for developing event handling programs
63. Program of ActionEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ActionEventExample" width=300 height=180>
</applet>
*/
public class ActionEventExample extends Applet implements
ActionListener
{
List obj1;
Button reset,submit;
String msg1 = "";
String msg2 = "";
public void init()
{
obj1 = new List(4,false);
obj1.add("First Sem");
obj1.add("Second Sem");
obj1.add("Third Sem");
obj1.add("Fourth Sem");
obj1.add("Fifth Sem");
submit = new Button("Submit");
add(obj1);
add(submit);
obj1.addActionListener(this);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
msg2 = ae.getActionCommand();
repaint();
}
// Show current selections.
public void paint(Graphics g) {
msg1 = "You have selected : ";
msg1 += obj1.getSelectedItem();
g.drawString(msg1,10,120);
if(msg2=="Submit")
{
msg2 = "Your data is submitted";
g.drawString(msg2, 6, 140);
}
}
}
78. Program of MouseWheelEvent
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="MouseWheelEventExample"
width=300 height=180>
</applet>
*/
public class MouseWheelEventExample extends
Applet implements MouseWheelListener
{
String msg = "";
int x=10,y=50;
public void init()
{
addMouseWheelListener(this);
}
public void
mouseWheelMoved(MouseWheelEvent mwe)
{
msg = "Mouse wheel is moving";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
79. Adapter classes
Java provides type of classes called as adapter classes which allows to process only
some events and not all events of a particular event listener
Adapter classes provides empty implementation of all methods in event listener
interfaces
For processing event using adapter classes, we have to :
Create a new class
Inherit one of the adapter classes
Implement only those methods or event in which we are intereseted
For example, KeyListener interface has three events - key pressed, key
released, and key typed, but we are only interested in key pressed event then
we can use KeyAdapter class in place of KeyListener
83. Inner classes
Inner classes are classes defined inside other classes or classes which are members
of another class
Inner classes are used to logically group together classes and interfaces
It makes the code more readable and maintainable
Inner classes can use the data members and functions (methods) of outer class,
including private data members and functions
Due to inner classes we have to write less code
84. Inner classes
class A ( outer class)
{
}
class B( inner class)
{
}
Fig. Inner class and outer class
85. Anonymous Inner classes
Anonymous inner classes are those inner classes which are not given names
Example :
import java.applet.*;
import java.awt.event.*;
public class AnonymousExample extends Applet
{
public void init( )
{
addKeyListener( new KeyAdapter( ) {
public void keyPressed(KeyEvent ke) {
showStatus("the key is pressed");
}
} );
}
}
inner class definition
without name