Transcript Events

Event Handling
For IST410 Students only
Events-1
Objectives




Concept of events
Event handling in Java
Action, Window and Mouse Events
Event Adapters
For IST410 Students only
Events-2
Event: Introduction




An event occurs when a user clicks a mouse button,
presses or releases a key, or in general, interacts with the
program
An event can be thought of as an external user action with
the program; the sequence of this interaction is user
dependent
User’s interaction is analogous to generating a signal to
the program and the program would be expected to
respond
It is then up to the program whether it responds or ignores
the event
For IST410 Students only
Events-3
Responding to an Event

A program, in order to respond to an event, must know
three important pieces of information about the event






What type of event occurred?
Which component originated the event?
Who gets notified when the event occurs?
A GUI component may be able to generate more than one
event type - for example, releasing a key generates a key
released and a key typed event
Many components on a GUI screen may generate the same
type of event - all buttons generate action events,
program’s response may differ from one button to another
We may designate an object to listen for the arrival of an
event i.e be notified
For IST410 Students only
Events-4
Event Models




An event model describes the mechanism of handling
events in a programming environment
In the old days (jdk1.0), Java’s event handling was
hierarchical - events were handled in the top layer of an
application
In the current model, the event handling is delegation
based - we delegate the responsibility of event handling for
a component to an object and we tell all (or who so ever
cares to listen) about it
Notice that in the delegation model, we can have any
number of objects responsible for event handling
For IST410 Students only
Events-5
What about the three pieces of
information?


How do Java programs deal with the three pieces of
information
What type of event occurred?


Which component originated the event?


This is easy. Java programs do not worry about it, but JVM does.
JVM recognizes the type of event and takes the responsibility of
notifying the designated greeter
This is a programming responsibility and we will see how to do
that
Who gets notified when an event occurs?

In some sense, JVM is the starting point of the notification cycle.
However, we designate Java objects as responsible parties to be
notified by JVM
For IST410 Students only
Events-6
Responding to an event






The notification process depends on registering an object
with a component for an event
The objects responsible for event handling are sometimes
called Listeners
Listeners are interface classes
Listeners declare abstract methods, each method is
associated with a predefined type of event
When JVM recognizes an event, it notifies the registered
listener which in turn executes the designated method
The program defines the response to an event by providing
content to the interface methods
For IST410 Students only
Events-7
Event Handling: Delegation Model
Frame
Panel or Frame Event
handlers
Panel
Mouse Click i.e. an
action event, can
occur with either
buttons
void actionPerformed(ActionEvent e) {
//
}
For IST410 Students only
Events-8
Basics of the Event Model




Listener: an object responsible for ‘listening’ for events
and responding
Registering Listener - add listener method of the GUI
component is used to register the listener object
Event source: The GUI component
Steps:




An user initiated event occurs: for example a mouse click
JVM recognizes an event
The event object is sent to the registered listener object for that
component
Listener object activates the handler method to respond
For IST410 Students only
Events-9
Listeners

Java defines a number of event listener Interfaces
Listener Type
Listens for
ActionListener
Action Events
ItemListener
Change in an item’s state
WindowListener
Window events
MouseListener
Mouse events
MouseMotionListener Mouse motion events
TextListener
Change in text value
and others....
For IST410 Students only
Events-10
Registering a Listener

Event sources may register one or more listeners


The current object is registered as a listener for a button named exit
exit.addActionListener(this);
A separate class MyWindowListener is registered as the listener for a
frame named jf
jf.addWindowListener(new MyWindowListener());


The registration process always takes the form
component.addListenerName(listenerObject);
A component can register multiple listener
jf.addWindowListener(new MyWindowListener());
jf.addMouseListener(this);
For IST410 Students only
Events-11
Listener Object


A listener object is an instance of a class that implements
the appropriate listener interface
exit.addActionListener(this);
 ‘this’ object is responsible for implementing the
ActionListener interface
Since the current class is responsible for action events
from the component exit, the class must be declared using
the following format
<modifier> class <class name> implements ActionListener { .... }
For IST410 Students only
Events-12
Listener Object


The listener interface may be implemented in a completely
separated class
jf.addWindowListener(new MyWindowListener());
 Listener is implemented in a separate class:
MyWindowListener
The listener class should be implemented using the
following format
<modifier> class <class name> implements WindowListener {
.........
}
For IST410 Students only
Events-13
Implementing a Listener





As you know, Listeners are interfaces
They declare abstract methods that an implementing class
must implement, or be itself treated as abstract
For event handling, an implementing class must implement
all abstract methods declared in the interface
Different interfaces define different abstract methods
For example, the only method defined in ActionListener
public void actionPerformed (ActionEvent e) {
//code to handle action events
}
For IST410 Students only
Events-14
Example: Event handler in the same
class as the event source
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleAction implements ActionListener {
SwingFrameWithExit jf;
Container cp;
SimpleAction declares the
JButton one, two, three;
intention of handling action
JButton exit;
events in this class
JPanel jp;
public SimpleAction() {
ImageIcon bullet = new ImageIcon("bullet2.gif");
ImageIcon middle = new ImageIcon("middle.gif");
jf = new SwingFrameWithExit();
cp = jf.getContentPane();
cp.setLayout(new BorderLayout(2,2));
For IST410 Students only
Events-15
Example: Event handler in the same
class as the event source
cp.setBackground(Color.red);
// create the Panel
jp = new JPanel();
jp.setBackground(Color.blue);
// create the buttons and add them to the panel
one = new JButton("ONE",bullet);
Registering event handler
jp.add(one);
for the GUI component
two = new JButton(middle);
exit; ‘this’ object is the
jp.add(two);
listener
three = new JButton("THREE",bullet);
jp.add(three);
cp.add(jp,BorderLayout.CENTER); // add panel to the frame
exit = new JButton("EXIT");
exit.addActionListener(this);
cp.add(exit,BorderLayout.SOUTH);
For IST410 Students only
Events-16
Example: Event handler in the same
class as the event source
jf.setSize(300,300);
jf.setVisible(true);
Implementation of the event
}
handling method; JVM notifies this
object (SimpleAction) about an
action event, which in turn fires
// Event handler for the Exit button
public void actionPerformed(ActionEvent e) { actionPerformed method and passes
an ActionEvent object to this
System.exit(0);
method
}
public static void main(String[] args) {
SimpleAction eac = new SimpleAction();
}
Code to respond to
the event, may be as
needed
}
For IST410 Students only
Events-17
Example: Event handler in a separate
class

Code is exactly same as the previous example: SimpleAction.java, only changes are
shown. The full source is in Example subdirectory for the module
......
No ‘implement’ here, since
public class SimpleActionSeparateClass {
a separate class does event
.....
handling
public SimpleActionSeparateClass() {
......
exit.addActionListener(new MyButtonHandler()); Registering by embedding
.......
the constructor of the listener
}
object
public static void main(String[] args) {
SimpleActionSeparateClass eac = new SimpleActionSeparateClass();
}
}
Separate class altogether,
class MyButtonHandler implements ActionListener {
// Event handler for the Exit button
does contain the
public void actionPerformed(ActionEvent e) {
actionPerformed method
System.exit(0);
though
}
}
For IST410 Students only
Events-18
Identifying source of Events




Source of an event can be identified in more than one way
By finding a reference to the source object itself
Object evtSource = e.getSource();
if (evtSource == exit) {
// response code
}
Necessary condition for this code to work
exit is a valid reference in the actionPerformed method
Not always possible in a large application
For IST410 Students only
Events-19
Identifying source of Action Events



An event source can be identified by comparing with the
command string
String s = e.getActionCommand();
if (“EXIT”equals(s)) {
// response code
}
The button or other action generating objects must have a
‘face’ string equal to “EXIT”
Not very convenient in a large program or for
internationalization
For IST410 Students only
Events-20
Identifying source of Action Events



A command string can be attached to an event source
exit.setActionCommand(“Close”);
The handler method can then compare with this String
String s = e.getActionCommand();
if (“Close”equals(s)) {
// response code
}
This technique is flexible, but program must ensure unique
command string names.
For IST410 Students only
Events-21
Example: Action event from multiple
sources
BorderLayoutEvents.java
For IST410 Students only
Events-22
WindowListener Interface





Window Listeners are used to trap Window events
We can use window events to monitor events with frames
and dialog boxes
The implementing class can be same as the class that
originates the events, or a separate class
Since the WindowListener interface defines 7 abstract
methods, the implementing class must implement all 7 of
them
The next slide shows an example of a window listener
class that can be registered to listen for window events

jf.addWindowListener(new MyWindowListener());
For IST410 Students only
Events-23
WindowListener Interface
import java.awt.event.*;
public class MyWindowListener implements WindowListener {
public void windowClosed(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
System.exit(0);
Only closing event is
}
implemented
}

Shows all methods of the Window Listener interface
For IST410 Students only
Events-24
Event handling through Adapters





MyWindowListener implements only one method
 windowClosing(WindowEvent e)
Six other methods of the WindowListener interface must
still be implemented even if all of these have empty actions
This approach is ‘bothersome’
Java provides adapter classes matching each listener class
where the listener has more than one abstract methods
For example, WindowListener has a corresponding
WindowAdapter class
For IST410 Students only
Events-25
Event handling through Adapters



Adapter classes are not abstract
These can be extended and only required method(s) can be
overridden
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
MyWindowAdapter class overrides the windowClosing
method and provides for exiting from an application.
For IST410 Students only
Events-26
Event handling through Adapters


All other methods of WindowAdapter class are then
inherited by the MyWindowAdapter; these inherited
methods have empty implementation
Such an adapter object can be registered as the event
handler for a frame using similar syntax as in the case of
the listener class object


jf.addWindowListener(new MyWindowAdapter());
Java provides adapter classes for all listeners with more
than one abstract method
For IST410 Students only
Events-27
Mouse Listener
Receives mouse events excluding motion
 Name of the interface is MouseListener
When called
void mouseClicked(MouseEvent e)
mouse is clicked
void mouseEntered(MouseEvent e)
enters a component
void mouseExited(MouseEvent e)
exits a component
void mousePressed(MouseEvent e)
mouse is pressed
void mouseReleased(MouseEvent e)
mouse is released
 Yes, there is a MouseAdapter class

For IST410 Students only
Events-28
Interesting methods of Mouse Event




int getClickCount() - gets you the number of mouse clicks
Point getPoint() - Returns the x,y coordinates of the
mouse event, These coordinates are screen coordinates in
pixels
int getX() - Returns the x coordinate of the event
int getY() - Returns the y coordinate of the event
For IST410 Students only
Events-29
Mouse Motion Listener
Interface to track Mouse Motion
 There is an equivalent MouseMotionAdapter class
 Since mouse motion events get constantly fired as a mouse
moves, efficiency dictates a separation between motion
and mouse down.
 Two event types
void mouseDragged(MouseEvent e) - fires when a mouse
button is pressed on a component and then dragged
void mouseMoved(MouseEvent e) - fires when the mouse
button is moved on a component without any button down

For IST410 Students only
Events-30
Example: Mouse Events
MouseEventDemo.java
For IST410 Students only
Events-31