0% found this document useful (0 votes)
86 views

Unit 8 Event Handling

The document discusses event handling in Java. It describes the delegation event model where event sources generate events that are passed to registered listener objects. It provides details on common event classes like ActionEvent, MouseEvent, and KeyEvent. It explains concepts like event types, event sources, and event listeners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Unit 8 Event Handling

The document discusses event handling in Java. It describes the delegation event model where event sources generate events that are passed to registered listener objects. It provides details on common event classes like ActionEvent, MouseEvent, and KeyEvent. It explains concepts like event types, event sources, and event listeners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit 8

Event Handling
Introduction
• Applet use GUI to interact with User and so it is event
driven.
• Events are supported by packages like java.awt, java.util
and java.awt.event.
• Most events are generated when user interacts with a GUI-
based program.
• There are several types of Events like
– Mouse clicked, dragged, or moved.
– Key from Keyboard is pressed.
– Checkbox selected or deselected.
– Window operations like close , iconified, deiconified etc.
– Scorllbar scrolls .
– Button is pushed.
Delegation Event Model
(Event Delegation Model) As an event source, my job is
to accept registrations (from
listeners), get events from the
Hey, what about me? I’m a
As a listener, my job is to player too, you know! As an user. And call the listener’s
implement the interface, event object, I’m the event-handling method
register with the button, and (when the user clicks me)
argument to the event call-
provide the event-handling.back method (from the

Listener interface) and my job is to


carry data about the event
back to the listener.
Source
Event

Listener GETS the Event object HOLDS DATA Source SENDS the event
event about the event
Delegation Event Model
“OK, you’re an ActionListener,
(Event Delegation Model)
Ok, Dear please
“Button, buttun,add
I got
methetoevent
your
so I know how to call you back
when there’s an event -- I’ll call
list of, listeners
now I have to and
changecall the the actionPerformed() method
my actionPerformed()
Background of the appletmethod
from that I know you have.”
whentothe
gray magenta.
user clicks you.”

Listener Source
Delegation Event Model
(Event Delegation Model)
• Advantage:
– Application logic that processes event is cleanly
separated from the user interface logic that
generates those events.
– User interface element is able to delegate the
processing of an event to a separate piece of code.
• Listener must register with a source to receive
an event notification.
– Benefit: notifications are sent only to listeners that
want to receive them.
Delegation Event Model
(Event Delegation Model)
• Event:
– Object that describes a state change in a source.
– Automatically generated when user interacts with GUI components or on some
special occasions like timer expires, a counter exceeds a value, a software or
hardware failure occurs or an operation is completed.
– Or you can manually generate using their constructors.
• Source
– Object that generates an event.
• When its internal state changes in some way.
– May generate more than one type of event.
– It must register listeners in order for the listeners to receive notifications about
specific type of event.
• Using methods
• public void addTypeListener( TypeListener el) // for multicasting
• ex.: public void addActionListener(ActionListener el)
• public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException
// for unicasting
Delegation Event Model
(Event Delegation Model)
• Event Listeners
– Object that is notified when an event occurs.
– It has two requirements:
• It must have been registered to one or more sources to receive
notifications about specific type of events.
• It must implement methods to receive and process these
notifications.
– Methods that receive and process events are defined in
a set of interfaces found in java.awt.event.
• Ex: MouseMotionListener interface declares two methods:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Event Class Hierarchy java.util.EventObject

java.awt.AwtEvent

ItemEvent AdjustmentEvent ComponentEvent ActionEvent TextEvent

FocusEvent

ContainerEvent InputEvent WindowEvent

KeyEvent

MouseEvent
Event Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu item is
selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.

ContainerEvent Generated when a component is added to or removed from a container.

FocusEvent Generated when a component gains or loses keyboard focus.

InputEvent Abstract super class for all component input event classes.

ItemEvent Generated when a check box or list item is clicked; also occurs when a choice selection is
made or a checkable menu item is selected or deselected.

KeyEvent Generated when input is received from the keyboard.


MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also
generated when the mouse enters or exits a component.

MouseWheelEvent Generated when the mouse wheel is moved. (Added byJava 2, version 1.4)

TextEvent Generated when the value of a text area or text field is changed.

WindowEvent Generated when a window is activated, closed, deactivated, deiconified, iconified,


opened, or quit.
ActionEvent
• Constants:
– ALT_MASK,
– CTRL_MASK,
– META_MASK,
– SHIFT_MASK, ACTION_PERFORMED.
• 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)
• Methods:
– String getActionCommand( )
– int getModifiers( )
– long getWhen( )
AdjustmentEvent
• Constants:
– BLOCK_DECREMENT
– BLOCK_INCREMENT
– TRACK
– UNIT_DECREMENT
– UNIT_INCREMENT
• Constructor:
– AdjustmentEvent(Adjustable src, int id, int type, int data)
• Methods:
– Adjustable getAdjustable( )
– int getAdjustmentType( )
– int getValue( )
ComponentEvent
• Constants:
– COMPONENT_HIDDEN
– COMPONENT_MOVED
– COMPONENT_RESIZED
– COMPONENT_SHOWN
• Constructor:
– ComponentEvent(Component src, int type)
• Method:
– Component getComponent( )
ContainerEvent
• Constants:
– COMPONENT_ADDED
– COMPONENT_REMOVED.
• Constructor:
– ContainerEvent(Component src, int type,
Component comp)
• Method:
– Container getContainer( )
– Component getChild( )
FocusEvent
• Constants:
– FOCUS_GAINED
– FOCUS_LOST
• Constructors:
– FocusEvent(Component src, int type)
– FocusEvent(Component src, int type, boolean
temporaryFlag)
– Focus Event(Component src, int type, boolean
temporaryFlag, Component other)
• Methods:
– Component getOppositeComponent( )
– boolean isTemporary( )
InputEvent
• Constants:
– ALT_MASK, BUTTON2_MASK, META_MASK,ALT_GRAPH_MASK,
BUTTON3_MASK SHIFT_MASK,,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
• Methods:
– boolean isAltDown( )
– boolean isAltGraphDown( )
– boolean isControlDown( )
– boolean isMetaDown( )
– boolean isShiftDown( )
– int getModifiers( )
– int getModifiersEx( )
ItemEvent
• Constants:
– DESELECTED
– SELECTED
• Constructor:
– ItemEvent(ItemSelectable src, int type, Object entry,
int state)
• Methods:
– Object getItem( )
– ItemSelectable getItemSelectable( )
– int getStateChange( )
KeyEvent
• Constants:
– KEY_PRESSED,KEY_RELEASED, KEY_TYPED, VK_0 through VK_9
and VK_A through VK_Z, 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, CHAR_UNDEFINED, VK_UNDEFINED.
• Constructor:
– KeyEvent(Component src, int type, long when, int modifiers, int
code)
– KeyEvent(Component src, int type, long when, int modifiers, int
code, char ch)
• Methods:
– char getKeyChar( )
– int getKeyCode( )
MouseEvent
• Constants:
– MOUSE_CLICKED,MOUSE_DRAGGED ,MOUSE_ENTERED ,MOUSE_EXITED ,
MOUSE_MOVED , MOUSE_PRESSED , MOUSE_RELEASED ,MOUSE_WHEEL,
NOBUTTON BUTTON1 BUTTON2 BUTTON3
• Constructor:
– MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks, boolean triggersPopup)
• Methods:
– int getX( )
– int getY( )
– Point getPoint( )
– void translatePoint(int x, int y)
– int getClickCount( )
– boolean isPopupTrigger( )
– int getButton( )
MouseWheelEvent
• Constants:
– WHEEL_BLOCK_SCROLL ,WHEEL_UNIT_SCROLL
• Constructor:
– MouseWheelEvent(Component src, int type, long
when, int modifiers, int x, int y, int clicks, boolean
triggersPopup, int scrollHow, int amount, int count)
• Methods:
– int getWheelRotation( )
– int getScrollType( )
– int getScrollAmount( )
TextEvent
• Constants:
– TEXT_VALUE_CHANGED
• Constructor:
– TextEvent(Object src, int type)
WindowEvent
• Constants:
– WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_CLOSING,
WINDOW_DEACTIVATED , WINDOW_DEICONIFIED ,
WINDOW_GAINED_FOCUS, WINDOW_ICONIFIED, WINDOW_LOST_FOCUS,
WINDOW_OPENED , WINDOW_STATE_CHANGED
• Constructors:
– WindowEvent(Window src, int type)
– WindowEvent(Window src, int type, int fromState, int toState)
– WindowEvent(Window src, int type, Window other, int fromState, int toState)
• Methods:
– Window getWindow( )
– Window getOppositeWindow()
– int getOldState()
– int getNewState()
Sources of Events
Event Source Description
Button Generates action event when the button is pressed.
Checkbox Generates item events when the check box is selected or
deselected.
Choice Generates item events when the choice is changed.
List Generates action event when an item is double-clicked; generates
item events when an item is selected or deselected.
Menu Item Generates action event when a menu item is selected; generates
item events when a checkable menu item is selected or deselected.
Scrollbar Generates adjustment event when the scroll bar is manipulated.
Text components Generates text event when the user enters a character.
Window Generates window event when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Event Listener Interfaces
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden, moved,
resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or loses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released, or
typed.
MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.

MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved. (Added
by Java 2, version 1.4)
TextListener Defines one method to recognize when a text value changes.
WindowFocusListener Defines two methods to recognize when a window gains or loses input
focus. (Added by Java 2, version 1.4)
WindowListener Defines seven methods to recognize when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
Event Listener Interfaces
• ActionListener
– void actionPerformed(ActionEvent ae)
• AdjustmentListener
– void adjustmentValueChanged(AdjustmentEvent ae)
• ComponentListener
– void componentResized(ComponentEvent ce)
– void componentMoved(ComponentEvent ce)
– void componentShown(ComponentEvent ce)
– void componentHidden(ComponentEvent ce)
• ContainerListener
– void componentAdded(ContainerEvent ce)
– void componentRemoved(ContainerEvent ce)
• FocusListener
– void focusGained(FocusEvent fe)
– void focusLost(FocusEvent fe)
Event Listener Interfaces
• ItemListener
– void itemStateChanged(ItemEvent ie)
• KeyListener
– void keyPressed(KeyEvent ke)
– void keyReleased(KeyEvent ke)
– void keyTyped(KeyEvent ke)
• MouseListener
– void mouseClicked(MouseEvent me)
– void mouseEntered(MouseEvent me)
– void mouseExited(MouseEvent me)
– void mousePressed(MouseEvent me)
– void mouseReleased(MouseEvent me)
• MouseMotionListener
– void mouseDragged(MouseEvent me)
– void mouseMoved(MouseEvent me)
Event Listener Interfaces
• MouseWheelListener
– void mouseWheelMoved(MouseWheelEvent mwe)
• TextListener
– void textChanged(TextEvent te)
• WindowFocusListener
– void windowGainedFocus(WindowEvent we)
– void windowLostFocus(WindowEvent we)
• WindowListener
– 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)
Implementing Delegation Event Model
• Two steps:
1. Implement the appropriate interface in the listener
so that it will receive the type of event desired.
2. Implement code to register and unregister (if
necessary) the listener as a recipient for the event
notifications.
• Each event must be registered separately.
• Also, 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.
import java.awt.*;
import java.awt.event.*; 1. Implement appropriate Listener (Register ) for event
import java.applet.*;
/* <applet code="MouseEvents" width=300 height=100> </applet> */
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0;
public void mouseClicked(MouseEvent me) {
mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint();
}
public void mouseEntered(MouseEvent me) {
mouseX = 0; mouseY = 10; msg = "Mouse entered.“; repaint();
}
public void mouseExited(MouseEvent me) {
mouseX = 0; mouseY = 10; msg = "Mouse exited.“; repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY(); msg = "Up“; repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = me.getX(); mouseY = me.getY(); msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me) {
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void init() {
addMouseListener(this); 2. Register the listener
addMouseMotionListener(this);
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
Handling Key Event
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="SimpleKey" width=300 height=100></applet>*/
public class SimpleKey extends Applet implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) { showStatus("Key Down"); }
public void keyReleased(KeyEvent ke) { showStatus("Key Up"); }
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g) { g.drawString(msg, X, Y); }
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="KeyEvents" width=300 height=100></applet>*/
public class KeyEvents extends Appletimplements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyReleased(KeyEvent ke) { showStatus("Key Up"); }
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
switch(ke.getKeyCode()) {
case KeyEvent.VK_F1:
msg += "<F1>“; break;
case KeyEvent.VK_F2:
msg += "<F2>“; break;
case KeyEvent.VK_F3:
msg += "<F3>“; break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>“; break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>“; break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>“; break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>"; break;
}
repaint();
}
}
Adapter class
• Simplify the creation of event handlers in certain
situations.
• It provides an empty implementation of all
methods in an event listener interface.
• useful when you want to receive and process only
some of the events.
• define a new class to act as an event listener by
extending one of the adapter classes
– & implementing only those events in which you are
interested.
Available Adapter Classes
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
import java.awt.*;
import java.awt.event.*;
import java.applet.*; Step 2: Register
/*<applet code="AdapterDemo" width=300 height=100> </applet> */
public class AdapterDemo extends Applet {
The listener
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo; Step 1: Create a
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
Listener
} Implement
public void mouseClicked(MouseEvent me) { The methods of
adapterDemo.showStatus("Mouse clicked"); listener interface.
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
Inner Classes
• inner class is a class defined within other class, or even
within an expression.
import java.applet.*;
import java.awt.event.*;
/*<applet code=" InnerClassDemo" width=200 height=100>
</applet> */
public class InnerClassDemo extends Applet { Step 2: Register
public void init() { The listener

addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
} Step 1: Create a
Listener
} Implement
} The methods of
listener interface.
Anonymous Inner Class
• 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");
}
} );
}
}
• new MouseAdapter( ) { ... } indicates to the compiler that the code
between the braces defines an anonymous inner class.

• Furthermore, that class extends MouseAdapter. This new class is not


named, but it is automatically instantiated when this expression is
executed

You might also like