Event Handling
Event Handling
Unit III
Event Handling
1
Topics and Sub-Topics
2
Outcomes
3
Event Handling
Any program that uses GUI (graphical user interface) such as Java application
Events are generated as result of user interaction with the graphical user
interface components.
the mouse, selecting an item from list, scrolling the page, etc.
and returns
5
Delegation Event Model
Advantage: Application logic for processing events are separated from GUI that
generates events
In this model, listener must register with source in order to receive an event
notification.
Events.
Event sources.
Event Listeners.
6
7
Events
An event is an object that describes a state change in a
source.
8
Events
Events may also occur that are not directly caused by
application.
9
Event Sources
A source is an object that generates an event.
in some way.
10
Event Sources
Here is the general form to register listeners:
Here, type is the name of the event, and el is a reference to the event
listener.
For example, the method that registers a keyboard event listener is
called addKeyListener().
The method that registers a mouse motion listener is called
addMouseMotionListener().
When an event occurs, all registered listeners are notified and
receive a copy of the event object.
11
Event Sources
The general form of unregister listener method is this:
removeKeyListener()
which is in java.util
Methods:
a subclass of EventObject.
15
16
Important Event Classes
and Interface
17
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is selected, ActionListener
list-item is double clicked
19
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
20
ActionEvent
An ActionEvent is generated when a button is pressed, a list item is double-clicked,
The ActionEvent class defines four integer constants that are used to identify any
modifiers associated with an action event:
An indicator that the alt key was held down during the event.
An indicator that the shift key was held down during the event.
An indicator that control key was held down during the event.
An indicator that the meta key was held down during the event. (The Meta key is
22
Constructor-2
public
ActionEvent(Object source,int id,String command,int modifiers)
23
Constructor-3
public
ActionEvent(Object source,int id,String command,long when,
int modifiers)
24
modifiers - the modifier keys held down during this action
Methods
public String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
String paramString()
Returns a parameter string identifying this action event.
25
ActionListener Interface
26
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
if(action.equals("Ok"))
actionMessage = "Ok Button Pressed";
else if(action.equals("Cancel"))
actionMessage = "Cancel Button Pressed";
repaint();
}
}
28
29
AdjustmentEvent
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
The AdjustmentEvent class defines integer constants that can be used to identify them.
BLOCK_DECREMENT
The user clicked inside the scroll bar to decrease its value.
BLOCK_INCREMENT
The user clicked inside the scroll bar to increase its value.
TRACK
UNIT_DECREMENT
The button at the end of the scroll bar was clicked to decrease its value.
UNIT_INCREMENT
The button at the end of the scroll bar was clicked to increase its value.
30
ADJUSTMENT_VALUE_CHANGED : indicates that a change has occured
AdjustmentEvent
Constructor: AdjustmentEvent(Adjustable src, int id, int
type, int data)
the event
Adjustable getAdjustable()
31
AdjustmentEvent
The type of the adjustment event may be obtained by the
int getAdjustmentType( )
33
ComponentEvent class
A low-level event which indicates that a component moved,
changed size, or changed visibility.
This class has following constants to identify the four types of component events.
the Component object that originated the event, or null if the object is not a
Component.
35
ComponentLIstener interface
void componentResized(ComponentEvent e)
void componentMoved(ComponentEvent e)
void componentShown(ComponentEvent e)
void componentHidden(ComponentEvent e)
This event indicates that a component was removed from the container.
37
Constructor:
Parameters:
38
Methods:
Returns the Container object that originated the event, or null if the
39
ContainerListener interface
void componentAdded(ContainerEvent e)
40
FocusEvent class
This event indicates that the Component is now the focus owner.
id - FOCUS_GAINED or FOCUS_LOST
43
FocusListener interface
void focusGained(FocusEvent e)
void focusLost(FocusEvent e)
44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public FocusListenerExample()
{
b1=new Button ("First");
b2=new Button ("Second");
add(b1,BorderLayout.SOUTH);
add(b2,BorderLayout.NORTH);
b1.addFocusListener(this);
b2.addFocusListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
45
public void focusGained(FocusEvent fe) //method of focuslistener
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"gained");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"gained");
if(fe.isTemporary())
System.out.println("Temporary Focus");
}
public void focusLost(FocusEvent fe) //in focusevent "getID()"is a method
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"lost");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"lost");
}
public static void main(String a[])
{
new FocusListenerExample();
}
46 }
47
InputEvent class
It is abstract class and is a subclass of ComponentEvent class
Its subclasses are KeyEvent and and MouseEvent
This class has following constants.
ALT_MASK
CTRL_MASK
META_MASK
ALT_GRAPH_MASK
SHIFT_MASK
BUTTON1_MASK
BUTTON2_MASK
BUTTON3_MASK
48
InputEvent class
Methods:
boolean isAltDown()
boolean isAltGraphDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
int getModifiers()
49
ItemEvent class
50
public ItemEvent (ItemSelectable source, int id,
Object item, int stateChange)
Constructs an ItemEvent object.
Parameters:
source - the ItemSelectable object that originated the event
id - an integer that identifies the event type
item - an object -- the item affected by the event
stateChange - an integer that indicates whether the item was selected
or deselected
51
Methods of ItemEvent Class
public ItemSelectable getItemSelectable()
Returns the creator of the event.
Returns: the ItemSelectable object that originated the event.
public Object getItem()
Returns the item affected by the event.
Returns: the item (object) that was affected by the event.
public int getStateChange()
Returns the type of state change (selected or deselected).
Returns: an integer that indicates whether the item was selected or
deselected
52
ItemListener interface
void itemStateChanged(ItemEvent e)
The code written for this method performs the operations that need
53
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
54
public void init()
{
java = new Checkbox("Java");
vb = new Checkbox("Visual Basic");
c = new Checkbox("C");
add(java);
add(vb);
add(c);
java.addItemListener(this);
vb.addItemListener(this);
c.addItemListener(this);
}
public void paint(Graphics g)
{
g.drawString("Java: " + java.getState(),10,80);
g.drawString("VB: " + vb.getState(), 10, 100);
g.drawString("C: " + c.getState(), 10, 120);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
55 }
}
56
KeyEvent class
An event which indicates that a keystroke occurred in a component.
produced by a single key press. Often, however, characters are produced by series
of key presses, and the mapping from key pressed events to key typed events may
be many-to-one or many-to-many.
57
There are many other integer constants that are defined
by KeyEvent. For example
VK_0 to VK_9
58
independent of any modifiers, such as control, shift, or alt.
Methods of KeyEvent class
Returns the integer keyCode associated with the key in this event.
For example, the KEY_TYPED event for shift + "a" returns the value for "A".
• boolean isActionKey()
Returns true if the key firing the event is an action key. Examples of action keys
include Page Up, Caps Lock, the arrow and function keys.
59
KeyListener Interface
Key events indicate when the user is typing at the keyboard.
Key events are fired by the component with the keyboard focus
60
The first kind of event is called a key-typed event.
sequence ?
To know when the user presses the F1 key, or whether the user
pressed the '3' key on the number pad, you handle key-pressed
events.
61
Methods of KeyListener Interface
Method Purpose
63
public void keyPressed(KeyEvent e) // handle key presses
{
event = e.getKeyChar() + " pressed"; repaint();
}
public void keyReleased(KeyEvent e) // handle key releases
{
event = e.getKeyChar() + " released"; repaint();
}
public void keyTyped(KeyEvent e) // handle typing on applet
{
event = e.getKeyChar() + " typed"; repaint();
}
}
64
TextEvent class
text changes.
Parameters:
65
TextListener interface
The code written for this method performs the operations that
66
WindowEvent class
A low-level event indicates that a window has changed its status.
WINDOW_ACTIVATED WINDOW_CLOSED
WINDOW_CLOSING WINDOW_DEACTIVATED
WINDOW_DEICONIFIED WINDOW_GAINED_FOCUS
WINDOW_ICONIFIED WINDOW_LOST_FOCUS
67
WINDOW_OPENED WINDOW_STATE_CHANGED
Constructors
public WindowEvent(Window source,int id)
Note that passing in an invalid id results in unspecified behavior. This method throws an
opposite - the other window involved in the focus or activation change, or null
oldState - previous state of the window for window state change event
newState - new state of the window for window state change event
68
Method
void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window from the window's system menu.
void windowClosed(WindowEvent e)
Invoked when a window has been closed as the result of calling dispose on the window
void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state. For many platforms, a minimized
window is displayed as the icon specified in the window's iconImage property.
void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
70
WindowFocusListener interface
The listener interface for receiving WindowEvents, including
WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events.
void windowGainedFocus(WindowEvent e)
void windowLostFocus(WindowEvent e)
75
Methods of MouseListener Interface
Method Purpose
Called just after the user clicks the listened-to
mouseClicked(MouseEvent)
component.
Called just after the cursor enters the bounds
mouseEntered(MouseEvent)
of the listened-to component.
Called just after the cursor exits the bounds of
mouseExited(MouseEvent)
the listened-to component.
Called just after the user presses a mouse
mousePressed(MouseEvent)
button while the cursor is over the listened-to
component.
Called just after the user releases a mouse
mouseReleased(MouseEvent) button after a mouse press over the listened-to
76 component.
MouseMotionListener Interface
Mouse-motion events notify when the user uses the mouse (or a similar
77
Methods of MouseMotionListener Interface
Method Purpose
78
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
79
public void paint(Graphics g) // draw message to screen
{
super.paint(g);
repaint();
80
}
public void mouseClicked(MouseEvent e) // save coordinates of clicks
{
x = e.getX();
y = e.getY();
event = "click";
repaint();
}
repaint();
}
81
public void mouseEntered(MouseEvent e) // save coordinates when mouse enters applet
{
x = e.getX();
y = e.getY();
event = "enter";
repaint();
}
repaint();
}
}
/*<applet code=MouseEventDemo height=300 width=300></applet>*/
82
Summary of Event Classes
& Listeners
83
84
85
86
87
Adapter Classes
Java provides a special feature, called an adapter class that can simplify the
creation of event handlers in certain situations.
An adapter class provides an empty implementation of all methods in an
event listener interface.
Adapter classes are useful when we want to receive and process only
some of the events that are handled by a particular event listener interface.
We can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which we are
interested.
For example, the MouseMotionAdapter class has two methods,
mouseDragged( ) and mouseMoved( ).
88