22 - Event Handling
22 - Event Handling
GRNICA 2
Two Event Handling Mechanisms
• Before beginning our discussion of event handling, an
important point must be made:
• The way events are handled by an applet changed
significantly between the original version of Java (1.0) and
modern versions of Java, beginning with version 1.1.
• The 1.0 method of event handling is still supported, but it is
not recommended for new programs. Also, many of the
methods that support the old 1.0 event model have been
deprecated.
GRNICA 3
The Delegation Event Model
• The modern approach to handling events is based on the
delegation event model.
• The delegation event model defines standard and consistent
mechanisms to generate and process events.
• Its concept is quite simple: a source generates an event and
sends it to one or more listeners. In this scheme, the listener
simply waits until it receives an event.
• Once received, the listener processes the event and then
returns.
• A user interface element is able to “delegate” the processing
of an event to a separate piece of code.
GRNICA 4
• In the delegation event model, listeners must register with a
source in order to receive an event notification because,
notifications are sent only to listeners that want to receive
them.
• Earlier, an event was propagated up the containment
hierarchy until it was handled by a component.
• This required components to receive events that they did not
process, and it wasted valuable time.
GRNICA 5
Events
• In the delegation model, an event is an object that describes a state
change in a source.
• It can be generated as a consequence of a person
interacting with the elements in a graphical user interface,
such as pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.
• Events may also occur that are not directly caused by
interactions with a user interface such as when a timer
expires, a counter exceeds a value, a software or a hardware
failure occurs.
GRNICA 6
Event Sources
• An event source is an object that generates an event.
Sources may generate more than one type of event.
• A source must register listeners in order for the listener to
receive notifications about a specific type of event. Each type
of event has its own registration method. Here is the general
form:
public void addTypeListener(TypeListener el)
• Here, Type is the name of the event, and el is a reference to
the event listener.
• 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.
GRNICA 7
• A source must also provide a method that allows a listener to
unregister an interest in a specific type of event. The general
form of such a method is this:
GRNICA 8
Event Listeners
• A listener is an object that is notified when an event occurs. It has two major requirements.
• First, it must have been registered with one or more sources
to receive notifications about specific types of events.
• Second, it must implement methods to receive and process
these notifications.
• The methods that receive and process events are defined in
a set of interfaces found in java.awt.event.
• For example, the MouseMotionListener interface defines
methods that receive notifications when the mouse is
dragged or moved.
GRNICA 9
Event Classes
• The classes that represent events are at the core of Java’s
event handling mechanism.
• At the root of the Java event class hierarchy is EventObject,
which is in java.util. It is the superclass for all events. Its one
constructor is shown here:
EventObject (Object src) – src is a reference to the object
that generates the event.
• EventObject contains two methods: getSource() & toString()
• The getSource() returns the source of event.
ObjectgetSource()
• The toString() returns the string equivalent of the event.
GRNICA 10
• EventObject is a supreclass of all events.
• AWTEvent, defined within the java.awt package is a subclass
of EventObject.
• AWTEvent is a superclass of all AWT events that are
handled by the delegation event model.
• getID() is a method used to determine the type of the event.
int getID()
GRNICA 11
GRNICA 12
The ActionEvent Class
• An ActionEvent is generated when a button is pressed, a list
item is double-clicked, or a menu item is selected.
• It defines four integer constants that can be used to identify
any modifiers associated with an action event : ALT_MASK,
CTRL_MASK, META_MASK and SHIFT_MASK.
• Addition to this there is an integer constant
ACTION_PERFORMED, used to identify action events.
• ActionEvent has three constructors:
GRNICA 13
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
GRNICA 14
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
• src : is a reference to the object that generated this event.
• type : specifies the type of event.
• cmd : getActionCommand() returns the command name for
invoking the ActionEvent object.
String getActionCommand()
• modifier : getModifier() method returns a value that indicates
which modifier keys (ALT, CTRL, and/or SHIFT) were pressed
when the event was generated.
int getModifiers()
• when : getWhen() returns the time at which the event took
place.
long getWhen()
GRNICA 15
The AdjustmentEvent Class
• 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 The slider was dragged
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.
GRNICA 16
• ADJUSTMENT_VALUE_CHANGED, an integer constant,
will indicate about any changes.
• It has a constructor by name AdjustmentEvent
AdjustmentEvent (Adjustable src, int id, int type, int data)
• src : is a reference to the object that generated this event.
getAdjustable() method returns the object that generated this
event.
Adjustable getAdjustable()
• id : id equals ADJUSTMENT_VALUE_CHANGED.
• type : specifies the type of the event & obtained by the
method getAdjustmentType()
int getAdjustmentType()
• getValue() returns the amount of adjustment.
GRNICA 17
The componentEvent Class
• A ComponentEvent is generated when the size, position or
visibility of a component is changed.
• The ComponentEvent class defines integer constants that
can be used to identify them.
GRNICA 18
• ComponentEvent has a constructor.
ComponentEvent (Component src, int type)
• src : is a reference to the object that generated this event.
• type : specifies the type of the event and obtained by the
method getComponent().
Component getComponent()
GRNICA 19
The ContainerEvent Class
• A ContainerEvent is generated when a component is added to or
removed from a container & there are two types of container
events.
• COMPONENT_ADDED and COMPONENT_REMOVED are the
two integer constants which indicate that a component has been
added to or removed from the container respectively.
• ContainerEvent is a subclass of ComponentEvent & has a
constructor as shown below:
ContainerEvent (Component src, int type, component comp)
• src : is a reference to the container that generated this event.
getContainer() method returns a reference to the container that
generated this event.
Container getContainer()
GRNICA 20
comp : specifies the component that has been added to or removed
from the container. getChild() method returns a reference to
the component that was added or removed from the container.
Component getChild()
GRNICA 21
The FocusEvent Class
• A FocusEvent is generated when a component gains or loses input
focus.
• These events are identified by the integer constants
FOCUS_GAINED and FOCUS_LOST.
• FocusEvent is a subclass of ComponentEvent and has these
constructors:
GRNICA 22
other component could be determined by getOppositeComponent().
Component getOppositeComponent()
• The isTemporary() method indicates if this change is temporary.
boolean isTemporary()
• Returns true if change is temporary, else false.
GRNICA 23
The InputEvent Class
• The abstract class InputEvent is a subclass of ComponentEvent and
is the superclass for input events.
• KeyEvent & MouseEvent are subclasses of InputEvent class.
• InputEvent defines several integer constants that represents any
modifiers such as ctrl key pressed….
BUTTON1_MASK CTRL_MASK
ALT_DOWN_MASK ALT_GRAPH_DOWN_MASK BUTTON1_DOWN_MASK
BUTTON2_DOWN_MASK BUTTON3_DOWN_MASK CTRL_DOWN_MASK
META_DOWN_MASK SHIFT_DOWN_MASK
GRNICA 24
• To test if a modifier was pressed at the time an event is generated,
use the below methods.
boolean isAltDown()
boolean isAltGraphDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()
• getModifers() method will return a value that contains all of the
original modifiers flags.
int getModifiers()
• Extended modifiers could be obtained by getModifiersEx() method
int getModifiersEx()
GRNICA 25
The ItemEvent Class
• An ItemEvent is generated when a check box or a list item is
clicked or when a checkable menu item is selected or deselected.
• DESELECTED & SELECTED are the two integer constants which
identifies two types of events for the user deselected & user selected
an item respectively.
• ITEM_STATE_CHANGED, an integer constant defines change of
state.
• ItemEvent has a constructor
ItemEvent(ItemSelectable src, int type, Object entry, int state)
• src : specifes a reference to the component that generate this event.
getItem() method is used to obtain a reference to the item that
generated an event.
Object getItem()
GRNICA 26
• The getItemSelectable() method can be used to obtain a reference
to the ItemSelectable object that generated an event.
ItemSelectable getItemSelectable()
GRNICA 27
The KeyEvent Class
• The KeyEvent is generated when keyboard input occurs.
• KEY_PRESSED, KEY_RELEASED, & KEY_TYPED are the three
integer constants which identify three types of key events.
• The first two are generated when a key is pressed or released. The
last event occurs when a character is generated.
• The integer constants like VK_0 through VK_9 & VK_A through
VK_Z are defined by KeyEvent define the ASCII equivalents of the
numbers and letters.
GRNICA 28
• KeyEvent is a sublcass of InputEvent. Here are its two contstructors
KeyEvent(Component src, int type , long when, int modifiers, int code)
KeyEvent(Component src, int type , long when, int modifiers, int code, char
ch)
• src : is a reference to the component that generated the event.
• type : specifies the type of the event.
• when : specifies the system time at which the key was pressed.
• modifiers : indicates which modifiers were pressed when this key
event occurred.
• code : specifies the virtual key code such as VK_UP, VK_A…
code is obtained by the method getKeyCode().
• ch : The character equivalent is passed in ch. If no valid character
exists, then ch contains CHAR_UNDEFINED. getKeyChar()
method returns the character that was generated.
GRNICA 29
The MouseEvent Class
• There are eight types of mouse event. The MouseEvent class
defines the following integer constants which identify them:
GRNICA 30
• MouseEvent is as subclass of InputEvent. It’s one of the constructor :
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks, boolean triggersPopup)
• src : is reference to the component that generated the event.
• type : type specifies the type of event.
• when : specifies the system time at which the mouse event occurred.
• modifiers : specifies which modifiers were pressed when a mouse
event occurred.
• x, y : The coordinates of the mouse. getX() & getY() are used.
Alternatively getPoint() method can be used to get the
coordinates of mouse.
Point getPoint()
The translatePoint() method changes the location of the event.
void translatePoint(int x, int y)
GRNICA 31
• click : specifies the click counts. It is obtained by getClickCount().
int getClickCount()
• triggerPopup : a flagindicates if this event causes a pop-up
menu to appear on this platform. It is obtained by
the method isPopupTrigger().
boolean isPopupTrigger()
GRNICA 32
The MouseWheelEvent Class
• The MouseWheelEvent Class encapsulates a mouse wheel event.
• It is a subclass of MouseEvent. MouseWheelEvent defines two
integer constants.
• WHEEL_BLOCK_SCROLL & WHEEL_UNIT_SCROLL are two
integer constants used for a page-up or page-down scroll event and
a line-up or line-down scroll event respectively.
MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y,
int clicks, boolean triggersPopup, int ScrollHow, int amount, int count)
• src : is reference to the component that generated the event.
• type : type specifies the type of event.
• when : specifies the system time at which the mouse event
occurred.
• modifiers : specifies which modifiers were pressed when a mouse
event occurred.
GRNICA 33
• x & y : used for the coordinates of the mouse.
• clicks : specifies the number of clicks the wheel has rotated.
Obtained by the method getWheelRotation().
GRNICA 34
The TextEvent Class
• Objects of this class describes text events. These are generated by
the text fields and text areas when characters are entered by a user
program.
• TEXT_VALUE_CHANGED is the integer constant which defines
the TestEvent.
TextEvent(Object src, int type)
• src : is reference to the component that generated the event.
• type : type specifies the type of event.
GRNICA 35
The WindowEvent Class
• Defines ten types of window events by integer constants.
GRNICA 37
Source of Events
Event Source Description
Button Generates action events when the button is pressed
Checkbox Generates item events when the check box is slected or
deselected
Choice Generates item events when the choice is changed
List Generates action events when an item is double-clicked;
generates item events when an item is selected or
deselected
Menu Item Generates action events when a menu item is selected;
generates item events when a checkable menu item is
selected or deselected.
Scrollbar Generates adjustment events when scroll bar is
manipulated.
Text components Generates text events when the user enters a character
Window Generates window events when a window is activated,
closed, deactivated, deiconified, iconified, opened or
quit GRNICA 38
Event Listener Interfaces
GRNICA 39
The ActionListener Interface
• Defines the actionPerformed() method that is invoked when an
action event occurs.
Void actionPerformed(ActionEvent ae)
GRNICA 40
The ContainerListener Interface
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
GRNICA 41
The MouseListener Interface
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
GRNICA 42
The TextListener Interface
void textChanged(TextEvent te) (change in text area / field )
GRNICA 43
Using the Delegation Event Model
• Applet programming using the delegation event model is actually
quite easy. Just follow these two steps:
• Remember that a source may generate several types of events. Each event must be
registered separately.
GRNICA 44
Handling Mouse Events
GRNICA 45
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
GRNICA 46
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
GRNICA 47
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
GRNICA 48
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
GRNICA 49
Handling Keyboard Events
GRNICA 50
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
GRNICA 51
Adapter Class
• Java provides a special feature called an adapter class, which
simplifies the creation of event handlers in certain situations.
• Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event
listener interface.
• For ex: mouseDragged() & mouseMoved() are two methods of
MouseMotionAdapter class.
• If we are interested in only mouse drag events, then we could
simply extend MouseMotionadapter and implement
mouseDragged().
GRNICA 52
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
GRNICA 53
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
GRNICA 54
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
GRNICA 55
class MyMouseMotionAdapter extends MouseMotionAdapter
{
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
GRNICA 56
Inner Class
import java.applet.*;
import java.awt.event.*;
/*<applet code="InnerClassDemo" width=200 height=100></applet>*/
public class InnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
} GRNICA 57
Here, InnerClassDemo is a top-level class that extends
Applet. MyMouseAdapter is an inner class that extends
MouseAdapter.
GRNICA 58
Anonymous Inner Classes
• An anonymous inner class is one that is not assigned a name.
import java.applet.*;
import java.awt.event.*;
/*<applet code="AnonymousInnerClassDemo" width=200 height=100></applet>*/
public class AnonymousInnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
});
}
}
GRNICA 59
There is one top-level class in this program:
AnonymousInnerClassDemo.
GRNICA 60