Unit 8 Event Handling
Unit 8 Event Handling
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 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
FocusEvent
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.
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.
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.
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.