Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

Event Handling

G A N E S H PA I
A S S T. P R O F E S S O R G D I I I
D E PA RT M E N T O F C S E
N M A M I T, N I T T E
Textbook
 Click to edit Master text styles
 Second level
 Third level
◦ Fourth level
◦ Fifth level

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 2


Overview of topics
 Introduction
 Delegation Event Model
 Event Classes
 Event Listener Interfaces
 Using the Delegation Event Model
 Adapter Classes
 Inner Classes

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 3


Event Handling  Changing the state of an object is known as an event
Introduction
 An event is a type of signal to the program that something has
Delegation Event Model happened
Event Classes  Any program that uses graphical user interface, such as a Java
Event Listener Interfaces application, is event driven
Using the Delegation Event Model  Most events to which programs respond are generated when the
Adapter Classes user interacts with a GUI-based program
Inner Classes  Example: click on button, dragging mouse, pressing a keyboard key

 In event-driven programming, code is executed upon activation of


events
 Program can respond to or ignore an event

 Each event may be associated with an event listener to execute the


registered handler containing the response task

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 4


Event Handling  In delegate event model, a source generates an event and
Introduction
sends it to one or more listeners
Delegation Event Model  The listener simply waits until it receives an event
Event Classes  Once received, the listener processes the event and then
Event Listener Interfaces returns
Using the Delegation Event Model  Design advantage: Processing events is separated from the
user interface logic that generates those events
Adapter Classes

Inner Classes  A user interface element is able to “delegate” the


processing of an event to a separate piece of code
 Listeners must register with a source in order to receive an
event notification.
 Design benefit: Notifications are sent only to listeners who
want to receive them

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 5


Delegation Event Model
Working
 Each event-generating object (component) maintains a set of listeners for each event that it generates.
 A listener object must register itself with the event-generating object to receive an event notification
public void addTypeListener(TypeListener el)
 Listeners have event-handling methods that respond to the event

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 6


Event
 An event is an object that describes a state change in a source.
 An event can be generated as a consequence of a person interacting with the elements in a
GUI.
 Activities causing events: pressing a button, entering a character via the keyboard, selecting
an item in a list, clicking the mouse, timer expires, a counter exceeds a value, a software or
hardware failure occurs, or an operation is completed.
 Package java.awt.event defines many types of events that are generated by various user
interface elements.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 7


Event Sources
 A 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 listeners to receive notifications about a
specific type of event.
 Each type of event has its own registration method.
 General form:
public void addTypeListener (TypeListener el )
TypeListener is the name of the event
el: reference to the event listener. For example,
 Ex.: Method that registers a keyboard event listener is called addKeyListener( ).
 Method that registers a mouse motion listener is called addMouseMotionListener( ).

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 8


Event Sources
 Multicasting event: When an event occurs, all registered listeners are notified and receive a copy of the event
object. One component to Many Listeners. Notifications are sent only to listeners that register to receive them.

 Unicasting event: Some sources may allow only one listener to register. The general form of method to register:

public void addTypeListener(TypeListener el ) throws java.util.TooManyListenersException

Type is the name of the event, el is a reference to the event listener.

 The same listener can listen to notifications from different objects. Many components to One Listener
Eve
Event Source1 nt o
 A source provides a method to allow listener to unregister an event. bjec
t1

Event Source2 Event object2 Event


Listener
 The general form to unregister: t3
objec
Event Source3 Event

public void removeTypeListener(TypeListener el )

 Ex.: To remove a keyboard listener, call removeKeyListener( ) on source object

 Component class provides methods to add and remove keyboard and mouse event listeners

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 9


Event Sources
• ActionEvent: Represents a graphical element is clicked, such as a button or item in a
list. Related listener: ActionListener.
• ContainerEvent: Represents an event that occurs to the GUI's container itself, for
example, if a user adds or removes an object from the interface. Related
listener: ContainerListener.
• KeyEvent: Represents an event in which the user presses, types or releases a
key. Related listener: KeyListener.
• WindowEvent: Represents an event relating to a window, for example, when a
window is closed, activated or deactivated. Related listener: WindowListener.
• MouseEvent: Represents any event related to a mouse, such as when a mouse is
clicked or pressed. Related listener: MouseListener.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 10


Event Sources
Button : Generates action events when the button is pressed.

Check box : Generates item events when the check box is selected 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.

Scroll bar : Generates adjustment events when the 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.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 11


Event Sources

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 12


Event Listener
 A listener is an object that is notified when an event occurs.
 Has two major requirements.
1. It must have been registered with one or more sources to receive notifications about
specific types of events.
2. It must implement methods to receive and process these notifications.

 The methods that receive and process events are defined in a set of interfaces
 Ex.: MouseMotionListener interface defines two methods to receive notifications when the
mouse is dragged or moved.
 Any object may receive and process one or both of these events if it provides an
implementation of this interface.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 13


Event Handling Event Classes Hierarchy
Introduction

Delegation Event Model

Event Classes

Event Listener Interfaces

Using the Delegation Event Model

Adapter Classes

Inner Classes

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 14


EventObject
 EventObject is the root of the Java event class hierarchy defined in java.util
 Is the superclass for all events.
 One constructor:
EventObject(Object src)
src is the object that generates this event.
 EventObject defines two methods: getSource( ) and toString( ).
 getSource( ): returns the source of the event. General form:
Object getSource( )
 toString( ): returns the string equivalent of the event
 class AWTEvent, defined in java.awt package, is a subclass of EventObject.
 Its getID( ) method: used to determine the type of event. The signature: int getID( )

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 15


Event Class – from java.awt.event

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 16


UI Sources of Events

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 17


1. ActionEvent Class
 ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
 Class defines four integer constants to identify any modifiers associated with an action event
 Event modifier constant:
 ALT_MASK
 CTRL_MASK
 META_MASK
 SHIFT_MASK
 ACTION_PERFORMED

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 18


1. ActionEvent Class
 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)
src: reference to the object that generated this event.
type: type of the event
cmd: its command string
modifiers: which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event
was generated.
when: specifies when the event occurred.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 19


1. ActionEvent Class
 Methods:
String getActionCommand() get the command name for the invoking ActionEvent object
int getModifiers( ) returns a value that indicates which modifier keys (alt, ctrl, meta, and/or
shift) were pressed when the event was generated
long getWhen( ) returns the time at which the event took place (event’s timestamp)

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 20


2. AdjustmentEvent Class
 AdjustmentEvent is generated by a scroll bar.
 5 Types

 ADJUSTMENT_VALUE_CHANGED: indicates that a change has occurred

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 21


2. AdjustmentEvent Class
 Constructor
AdjustmentEvent (Adjustable src, int id, int type, int data)
src: reference to the object that generated this event.
id: ADJUSTMENT_VALUE_CHANGED.
type: type of the event
data: its associated data
 Methods
Adjustable getAdjustable( ) Returns the object that generated the event

int getAdjustmentType( ) Returns type of the adjustment event

int getValue( ) Returns amount of the adjustment. Returns the value represented by the
change

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 22


3. ComponentEvent Class
 ComponentEvent is generated when the size, position, or visibility of a component is changed
 4 types of events:

 Constructor:
ComponentEvent(Component src, int type)
src: reference to the object that generated this event.
type: type of the event
 Methods:
Component getComponent( ): returns the component that generated the event

 ComponentEvent is the superclass of


[ ContainerEvent, FocusEvent, KeyEvent, MouseEvent, WindowEvent ]
Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 23
4. ContainerEvent Class
 ContainerEvent is generated when a component is added to or removed from a container.
 2 Types of events:
 COMPONENT_ADDED
container
 COMPONENT_REMOVED
 Constructor:
ContainerEvent(Component src, int type, Component comp)
src: reference to the container that generated this event.
type: type of the event
comp: component that has been added to or removed from the container
 Methods: Container getContainer( ) returns reference to the container that generated this event

Component getChild( ) returns a reference to the component that was added to or


removed from the container

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 24


5. FocusEvent Class
 FocusEvent is generated when a component gains or loses input focus
 2 Types of events:
 FOCUS_GAINED
 FOCUS_LOST
 Constructors:

src: reference to the component that generated this event.


type: type of the event.
temporaryFlag: set to true if the focus event is temporary. Otherwise, it is set to false.
other: other component involved in the focus change, called the opposite component. If a
FOCUS_GAINED event occurred, other will refer to the component that lost focus. Conversely, if a
FOCUS_LOST event occurred, other will refer to the component that gains focus.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 25


5. FocusEvent Class
 Methods:
Component getOppositeComponent( ) opposite component is returned

boolean isTemporary( ) returns true if the change is temporary. Otherwise, it returns false

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 26


6. InputEvent Class
 Abstract class InputEvent is a subclass of ComponentEvent and superclass for component
input events KeyEvent and MouseEvent.
 Integer constants representing modifiers associated with the event:
 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

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 27


6. InputEvent Class
 Methods to test if a modifier was pressed at the time an event is generated
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
int getModifiersEx( ): obtain the extended modifiers

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 28


7. KeyEvent Class
 KeyEvent is generated when keyboard input occurs
 3 Types of key events
 KEY_PRESSED : occurs when a key is pressed
 KEY_RELEASED : occurs when a key is released
 KEY_TYPED : occurs when a character is generated
 VK constants specify virtual key codes and are independent of any modifiers
VK_ENTER VK_ESCAPE VK_CANCEL
VK_UP VK_DOWN VK_LEFT
VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP
VK_SHIFT VK_ALT VK_CONTROL
VK_0 through VK_9 VK_A through VK_Z

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 29


7. KeyEvent Class
 Constructors:
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: reference to the component that generated the event.
type: type of the event
when: system time at which the key was pressed
modifiers: indicates which modifiers were pressed when this key event occurred.
code: virtual key code. For KEY_TYPED events, code will contain VK_UNDEFINED.
ch: character equivalent (if one exists). If no valid character exists, then ch contains
CHAR_UNDEFINED.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 30


7. KeyEvent Class
 Methods:
char getKeyChar( ) returns CHAR_UNDEFINED if no valid character is available

int getKeyCode( ) returns VK_UNDEFINED when KEY_TYPED event occurs

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 31


8. MouseEvent Class
 8 types of mouse events:

 Constructors:
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)
src: reference to the component that generated the event.
type: type of the event
when: system time at which the mouse event occurred
modifiers: indicates which modifiers were pressed when a mouse event occurred.
x and y: The coordinates of the mous.
clicks: The click count
triggersPopup: flag indicates if this event causes a pop-up menu to appear on this platform.
Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 32
8. MouseEvent Class
 Methods:
int getX( ) Return the X coordinates of the mouse within the component when the event
occurred
int getY( ) Return the Y coordinates of the mouse within the component when the event
occurred
Point getPoint( ) Returns a Point object that contains the X,Y coordinates of the mouse, in its
integer members: x and y
void translatePoint(int x, int y) Changes the location of the event. Arguments x and y are added to the
coordinates of the event.
int getClickCount( ) Returns number of mouse clicks for this event
boolean isPopupTrigger( ) Tests if this event causes a pop-up menu to appear on this platform
int getButton( ) Returns a value representing the button that caused the event.
In most cases, value will be one of constants defined by MouseEvent:
NOBUTTON, BUTTON1, BUTTON2, BUTTON3
NOBUTTON value indicates that no button was pressed or released
Point getLocationOnScreen( )
int getXOnScreen( ) Returns coordinates of the mouse relative to the screen
int getYOnScreen( )

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 33


9. MouseWheelEvent Class
 MouseWheelEvent class encapsulates a mouse wheel event
 It is a subclass of MouseEvent
 Occurs when mouse wheel is scrolled

 2 Integer Constants
 WHEEL_BLOCK_SCROLL

 Occurs when page-up or page-down scroll event occurred

 WHEEL_UNIT_SCROLL

 Occurs when line-up or line-down scroll event occurred

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 34


9. MouseWheelEvent Class
 Constructors:

MouseWheelEvent (Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean
triggersPopup, int scrollHow, int amount, int count)
src: reference to the object that generated the event.
type: The type of the event.
when: The system time at which the mouse event occurred
modifiers: indicates which modifiers were pressed when the event occurred.
x and y: The coordinates of the mouse
clicks: The number of clicks the wheel has rotated.
triggersPopup: flag indicates if this event causes a pop-up menu to appear on this platform.
scrollHow: value must be either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
amount: The number of units to scroll is passed in.
count: the number of rotational units that the wheel moved.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 35


9. MouseWheelEvent Class
 Methods:
int getWheelRotation( ) Returns number of rotational units
int getScrollType( ) Returns the type of scroll.
Returns either WHEEL_UNIT_SCROLL or WHEEL_BLOCK_SCROLL.
If the scroll type is WHEEL_UNIT_SCROLL, one can obtain the number of
units to scroll by calling getScrollAmount( ).
int getScrollAmount( ) Returns the number of units to scroll

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 36


10. ItemEvent Class
 ItemEvent is generated when a check box or a list item is clicked or when a checkable menu
item is selected or deselected
 2 Types of Events
 DESELECTED
 SELECTED
 ITEM_STATE_CHANGED
 Constructors:
ItemEvent(ItemSelectable src, int type, Object entry, int state)
src: reference to the component that generated this event. (this might be a list or choice element.)
type: type of the event.
entry: specific item that generated the item event.
state: The current state of that item

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 37


10. ItemEvent Class
 Methods:
Object getItem( ) used to obtain a reference to the item that changed
ItemSelectable getItemSelectable( ) used to obtain a reference to the ItemSelectable object that
generated an event. Lists and choices are examples of user interface
elements that implement the ItemSelectable interface
int getStateChange( ) returns the state change (that is, SELECTED or DESELECTED) for the
event

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 38


11. TextEvent Class
 These are generated by text fields and text areas when characters are entered by a user or
program
 Integer Constant: TEXT_VALUE_CHANGED
 Constructor
TextEvent(Object src, int type)
src: reference to the object that generated this event.
type: The type of the event

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 39


12. WindowEvent Class
 10 types of window events

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 40


12. WindowEvent Class
 Constructors:
WindowEvent(Window src, int type)
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)
src: reference to the object that generated this event.
type: The type of the event
other: specifies the opposite window when a focus event occurs.
fromState: specifies the prior state of the window
toState: specifies the new state that the window will have when a window state change occurs

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 41


12. WindowEvent Class
 Methods:
Window getWindow( ) Returns the Window object that generated the event
Window getOppositeWindow() Return the opposite window (when a focus or activation event has
occurred)
int getOldState() Returns previous window state
int getNewState() Returns current window state

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 42


Event Handling  Any object that wishes to respond to an event must implement a
Introduction
listener interface.
Delegation Event Model

Event Classes

Event Listener Interfaces

Using the Delegation Event Model

Adapter Classes

Inner Classes

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 43


Event Listener Interfaces
 ActionListener Interface
 void actionPerformed(ActionEvent ae)
 AdjustmentListener Interface
 void adjustmentValueChanged(AdjustmentEvent ae)
 ComponentListener Interface
 void componentResized(ComponentEvent ce)
 void componentMoved(ComponentEvent ce)
 void componentShown(ComponentEvent ce)
 void componentHidden(ComponentEvent ce)
 ContainerListener Interface
 void componentAdded(ContainerEvent ce)
 void componentRemoved(ContainerEvent ce)

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 44


Event Listener Interfaces
 FocusListener Interface
 void focusGained(FocusEvent fe)
 void focusLost(FocusEvent fe)
 ItemListener Interface
 void itemStateChanged(ItemEvent ie)
 KeyListener Interface
 void keyPressed(KeyEvent ke)
 void keyReleased(KeyEvent ke)
 void keyTyped(KeyEvent ke)

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 45


Event Listener Interfaces
 MouseListener Interface
 void mouseClicked(MouseEvent me)
 void mouseEntered(MouseEvent me)
 void mouseExited(MouseEvent me)
 void mousePressed(MouseEvent me)
 void mouseReleased(MouseEvent me)
 MouseMotionListener Interface
 void mouseDragged(MouseEvent me)
 void mouseMoved(MouseEvent me)
 MouseWheelListener Interface
 void mouseWheelMoved(MouseWheelEvent mwe)
 TextListener Interface
 void textChanged(TextEvent te)

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 46


Event Listener Interfaces
 WindowFocusListener Interface
 void windowGainedFocus(WindowEvent we)
 void windowLostFocus(WindowEvent we)
 WindowListener Interface
 void windowActivated(WindowEvent we)
 void windowClosed(WindowEvent we)
 void windowClosing(WindowEvent we)
 void windowDeactivated(WindowEvent we)
 void windowDeiconified(WindowEvent we)
 void windowIconified(WindowEvent we)
 void windowOpened(WindowEvent we)

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 47


Event Handling  Steps to use delegation event model
Introduction 1. Implement the appropriate interface in the listener so
that it can receive the type of event desired.
Delegation Event Model
2. Implement code to register and unregister (if
Event Classes necessary) the listener as a recipient for the event
Event Listener Interfaces notifications.
Using the Delegation Event Model  Source may generate several types of events.
Adapter Classes
 Each event must be registered separately.
Inner Classes
 An object may register to receive several types of events,
but it must implement all of the interfaces that are
required to receive these events.
 Examples Covered: Mouse and Keyboard event handling

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 48


Using the Delegation Event Model
 Implementation:

public class MyButtonListener implements ActionListener { … }


 JButton needs ActionListener
JButton b1 = new JButton(“Button”);
b1.addActionListener(new MyButtonListener ( ));
 Implementing interface necessitates implementation on all interface methods

 ActionListener object must have an actionPerformed(ActionEvent) method. Hence, MyButtonListener


need to have

public void actionPerformed(ActionEvent e)

{

}

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 49


Says MyButtonListener class will
Using the Delegation Event Model listen to ActionEvents

 Complete Structure: public class MyButtonListener implements ActionListener


public class MyApp { …
{ … public void actionPerformed(ActionEvent e)
onclick
JButton b1 = new JButton(“Button”); Button {
Event Handler
//do something here
b1.addActionListener(new MyButtonListener()); What is to be
}
done when
… Click event creates button is clicked
} ActionEvent object
} and sends to

Registering listener object


Says if b1 generates ActionEvents (click event), send
the signal to MyButtonListener object to handle it.
It calls actionPerformed() method of this object

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 50


Using the Delegation Event Model
 Complete Structure (Same class handling events):
public class MyApp implements ActionListener
{

Button JButton b1 = new JButton(“Button”);
b1.addActionListener(this);

public void actionPerformed(ActionEvent e)
{
… //do something here
}
}

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 51


Using the Delegation Event Model
 Handling Mouse Events Program
 As the mouse enters or exits the applet window, a message is displayed in the upper-left
corner of the applet display area.
 When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is
dragged.
 Two variables mouseX and mouseY store the location of the mouse when a mouse
pressed, released, or dragged event occurs.
 These coordinates are then used by paint( ) to display output at the point of these
occurrences.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 52


// Demonstrate the mouse event handlers. public void mouseExited(MouseEvent me) { // Handle mouse exited
import java.awt.*; mouseX = 0; mouseY = 10;
import java.awt.event.*; msg = "Mouse exited.";
import java.applet.*; repaint();
}
public class MouseEvents .
extends Applet public void mousePressed(MouseEvent me) { // Handle button pressed
implements MouseListener, MouseMotionListener { mouseX = me.getX();
mouseY = me.getY();
String msg = ""; msg = "Down";
int mouseX = 0, mouseY = 0; // coordinates of mouse repaint();
}
public void init() {
addMouseListener(this); public void mouseReleased(MouseEvent me) { // Handle button released
addMouseMotionListener(this); mouseX = me.getX();
} mouseY = me.getY();
msg = "Up";
public void paint(Graphics g) // Display msg in applet window at X, Y location repaint();
{ }
g.drawString(msg, mouseX, mouseY);
} public void mouseDragged(MouseEvent me) { // Handle mouse dragged
mouseX = me.getX();
public void mouseClicked(MouseEvent me) { // Handle mouse clicked mouseY = me.getY();
mouseX = 0; mouseY = 10; msg = "*";
msg = "Mouse clicked."; showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint(); repaint();
} }

public void mouseEntered(MouseEvent me) { // Handle mouse entered. public void mouseMoved(MouseEvent me) { // Handle mouse moved
mouseX = 0; mouseY = 10; showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
msg = "Mouse entered."; }
repaint(); }
}
Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 53
Using the Delegation Event Model
 Handling Keyboard Events Program
 KeyListener interface need to be implementing
 When a key is pressed, a KEY_PRESSED event is generated resulting a call to the keyPressed( ) event
handler.
 When the key is released, a KEY_RELEASED event is generated and keyReleased( ) handler is
executed.
 If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( )
handler is invoked.
 Each time the user presses a key, at least two and often three events are generated.
 If actual characters are of interest, then key press and release events can be ignored.
 If program needs to handle special keys, such as the arrow or function keys, it must watch for them
through the keyPressed( ) handler
 The program echoes keystrokes to the applet window and shows the pressed/released status of each
key in the status window.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 54


Using the Delegation Event Model
// Demonstrate some virtual key codes. public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
import java.awt.*; switch(ke.getKeyCode())
import java.awt.event.*; {
import java.applet.*; case KeyEvent.VK_F1: msg += "<F1>"; break;
case KeyEvent.VK_F2: msg += "<F2>"; break;
public class KeyEvents extends Applet case KeyEvent.VK_F3: msg += "<F3>"; break;
implements KeyListener { case KeyEvent.VK_PAGE_DOWN: msg += "<PgDn>"; break;
String msg = ""; case KeyEvent.VK_PAGE_UP: msg += "<PgUp>"; break;
int X = 10, Y = 20; // output coordinates case KeyEvent.VK_LEFT: msg += "<Left Arrow>"; break;
case KeyEvent.VK_RIGHT: msg += "<Right Arrow>"; break;
public void init() { }
addKeyListener(this); repaint();
requestFocus(); // request input focus }
}
public void keyReleased(KeyEvent ke) {
public void paint(Graphics g) { showStatus("Key Up");
g.drawString(msg, X, Y); }
} }

public void keyTyped(KeyEvent ke) {


msg += ke.getKeyChar();
repaint();
}
Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 55
 An adapter class provides an empty implementation of all methods
Event Handling in an event listener interface.
Introduction  Adapter classes are useful when you want to receive and process
Delegation Event Model only some of the events that are handled by a particular event
listener interface.
Event Classes

Event Listener Interfaces


 You can define a new class to act as an event listener by extending
one of the adapter classes and implementing only those events in
Using the Delegation Event Model which you are interested.
Adapter Classes
 Ex.: MouseMotionAdapter class has two methods,
Inner Classes  mouseDragged( )
 mouseMoved( )
 The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface.
 If you are interested in only mouse drag events, then, you can
extend MouseMotionAdapter and implement mouseDragged( )
 The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.
Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 56
Adapter Classes
 Adapter Class vs Listener Interface

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 57


Adapter Classes - Implementation

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 58


Event Handling  An inner class is a class defined within another class, or
Introduction even within an expression
Delegation Event Model  Ex.: Goal is to display the string "Mouse Pressed“ in the
Event Classes status bar of the applet viewer or browser when the mouse
Event Listener Interfaces
is pressed.
Using the Delegation Event Model  There are two top-level classes in this program.
Adapter Classes  MousePressedDemo extends Applet
Inner Classes  MyMouseAdapter extends MouseAdapter
 The init( ) method of MousePressedDemo instantiates
MyMouseAdapter and provides this object as an argument
to the addMouseListener( ) method.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 59


Inner Classes
 Without Inner class

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 60


Inner Classes
 With Inner class

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 61


Inner Classes
 With Anonymous Inner Classes
 An anonymous inner class is a class that is not assigned a name.

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 62


End of
Event Handling

Event Handling GANESH PAI, DEPT. OF CSE, NMAMIT, NITTE 63

You might also like