Event Handling PDF
Event Handling PDF
1
Introduction
• To respond to a button click, you need to write the
code to process the button-clicking action.
• The button is an event source object, where the
action originates.
2
Introduction
• The object must be an instance of the
ActionListener interface.
• The ActionListener object listener must be
registered with the event source object using the
method source.addActionListener(listener).
• The ActionListener interface contains the
actionPerformed method for processing the
event.
• Your listener class must override this method to
respond to the event.
• The following program gives the code that
processes the ActionEvent on the two buttons (Ok
3
Introduction
import javax.swing.*;
import java.awt.event.*;
public class HandleEvent extends JFrame {
public HandleEvent() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new JButton("Cancel");
// Register listeners
OkListenerClass listener1 = new OkListenerClass();
CancelListenerClass listener2 = new CancelListenerClass();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2); Register
} Listener
4
Introduction
public static void main(String[] args) {
JFrame frame = new HandleEvent();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} Listener Class
}
class OkListenerClass implemets ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}
Listener Class
Process Event
class CancelListenerClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Cancel button clicked");
}
}
5
Introduction
• The above program defines two listener classes.
• Each listener class implements ActionListener to process
ActionEvent.
• The object listener1 is an instance of OKListenerClass,
which is registered with the button jbtOK.
• When the OK button is clicked, the
actionPerformed(ActionEvent) method in OKListenerClass
is invoked to process the event.
• The object listener2 is an instance of CancelListenerClass,
which is registered with the button jbtCancel.
• When the Cancel button is clicked, the
actionPerformed(ActionEvent) method in
CancelListenerClass is invoked to process the event.
6
Events and Event Sources
• An event is an object created from an event source.
• Firing an event means to create an event and delegate the
listener to handle the event.
• When you run a Java GUI program, the program interacts
with the user, and the events drive its execution.
• This is called event-driven programming.
• An event can be defined as a signal to the program that
something has happened.
• Events are triggered either by external user actions, such as
mouse movements, button clicks, and keystrokes, or by
internal program activities, such as a timer.
• The program can choose to respond to or ignore an event.
7
Events and Event Sources
The component that creates an event and fires it is
called the event source object, or simply
• source object or source component.
• For example, a button is the source object for a
button clicking action event.
• An event is an instance of an event class.
• The root class of the event classes is
java.util.EventObject.
8
Event Classes
• The hierarchical relationships of some event classes.
9
Event Information
• An event object contains whatever properties are
pertinent to the event.
• You can identify the source object of the event
using the getSource() instance method in the
EventObject class.
• The subclasses of EventObject deal with special
types of events, such as button actions, window
events, component events, mouse movements, and
keystrokes.
• Following table lists external user actions, source
objects, and event types generated. 10
Selected User Actions
Source Event Type
User Action Object Generated
12
The Delegation Model
13
The Delegation Model
• The listener object must be an instance of the corresponding
event-listener interface to ensure that the listener has the
correct method for processing the event.
• The listener interface is usually named XListener for
XEvent, with the exception of MouseMotionListener.
• The listener interface contains the method(s), known as the
event handler(s), for processing the event.
• For example, as shown in the first line of the above table, the
corresponding listener interface for ActionEvent is
ActionListener; each listener for ActionEvent should
implement the ActionListener interface; the ActionListener
interface contains the handler
actionPerformed(ActionEvent) for processing an
ActionEvent. 14
The Delegation Model
• The listener object must be registered by the source
object.
• Registration methods depend on the event type.
• For ActionEvent, the method is
addActionListener.
• In general, the method is named addXListener for
XEvent.
15
Internal Function of a Source Component
16
The Delegation Model: Example
17
Selected Event Handlers
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
MouseEvent MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
18
java.awt.event.ActionEvent
19
Inner Class Listeners
• An inner class, or nested class, is a class defined within
the scope of another class.
• Inner classes are useful for defining listener classes.
20
Inner Class Listeners
• An inner class has the following features:
An inner class supports the work of its containing outer class and
is compiled into a class named
OuterClassName$InnerClassName.class. For example, the inner
class InnerClass in OuterClass is compiled into
OuterClass$InnerClass.class.
An inner class can reference the data and methods defined in the
outer class in which it nests, so you need not pass the reference of
an object of the outer class to the constructor of the inner class.
Inner classes can make programs simple and concise.
An inner class can be declared public, protected, or private
subject to the same visibility rules applied to a member of the
class.
21
Inner Class Listeners
An inner class can be declared static. A static inner class can be accessed
using the outer class name. A static inner class cannot access nonstatic
members of the outer class.
Objects of an inner class are often created in the outer class. But you can
also create an object of an inner class from another class. If the inner class
is nonstatic, you must first create an instance of the outer class, then use
the following syntax to create an object for the inner class:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
If the inner class is static, use the following syntax to create an object for it:
OuterClass.InnerClass innerObject = new OuterClass.InnerClass();
22
Inner Classes, cont…
23
Anonymous Inner Classes
• An anonymous inner class is an inner class without a name. It combines
defining an inner class and creating an instance of the class into one step.
• Inner-class listeners can be shortened using anonymous inner classes.
• An anonymous inner class must always extend a superclass or implement
an interface, but it cannot have an explicit extends or implements clause.
• An anonymous inner class must implement all the abstract methods in the
superclass or in the interface.
• An anonymous inner class always uses the no-arg constructor from its
superclass to create an instance. If an anonymous inner class implements
an interface, the constructor is Object().
24
Anonymous Inner Classes (cont.)
• Inner class listeners can be shortened using
anonymous inner classes. An anonymous inner
class is an inner class without a name. It combines
declaring an inner class and creating an instance
of the class in one step. An anonymous inner class
is declared as follows:
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass or interface
// Other methods if necessary
}
25
Anonymous Inner Classes (cont.)
26
Anonymous Inner Classes
// Create a panel to hold buttons
import javax.swing.*; JPanel panel = new JPanel();
import java.awt.event.*; panel.add(jbtNew);
public class panel.add(jbtOpen);
AnonymousListenerDemo extends panel.add(jbtSave);
JFrame { panel.add(jbtPrint);
public AnonymousListenerDemo() add(panel);
{ // Create and register anonymous
// Create four buttons inner-class listener
JButton jbtNew = new
jbtNew.addActionListener(new
JButton("New");
ActionListener(){
JButton jbtOpen = new
JButton("Open"); @Override
JButton jbtSave = new public void
JButton("Save"); actionPerformed(ActionEvent e){
JButton jbtPrint = new System.out.println(“Process
JButton("Print"); New”);
}
}
);
27
Anonymous Inner Classes
jbtOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Process Open");
} } );
jbtSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Process Save");
} } );
jbtPrint.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Process Print");
} } );
} 28
Anonymous Inner Classes
29
Anonymous Inner Classes
• The program creates four listeners using
anonymous inner classes.
• Without using anonymous inner classes, you
would have to create four separate classes.
• An anonymous listener works the same way as an
inner class listener.
• The program is condensed using an anonymous
inner class.
• Anonymous inner classes are compiled into
OuterClassName$#.class, where # starts at 1 and
is incremented for each anonymous class the
compiler encounters.
30
Anonymous Inner Classes
• In this example, the anonymous inner classes are
compiled into AnonymousListenerDemo$1.class,
AnonymousListenerDemo$2.class,
AnonymousListenerDemo$3.class, and
AnonymousListenerDemo$4.class.
33
Mouse Event
• Since the MouseEvent class inherits InputEvent, you
can use the methods defined in the InputEvent class on a
MouseEvent object.
• For example, the isControlDown() method detects
whether the CTRL key was pressed when a MouseEvent
is fired.
• Three int constants—BUTTON1, BUTTON2, and
BUTTON3—are defined in MouseEvent to indicate the
left, middle, and right mouse buttons. You can use the
getButton() method to detect which button is pressed.
• For example, getButton() == MouseEvent.BUTTON3
indicates that the right button was pressed. 34
Handling Mouse Events
• Java provides two listener interfaces,
MouseListener and
MouseMotionListener, to handle mouse
events.
• The MouseListener listens for actions such as
when the mouse is pressed, released, entered,
exited, or clicked.
• The MouseMotionListener listens for
actions such as dragging or moving the mouse.
35
Handling Mouse Events
The MouseListener interface handles mouse pressed, released, clicked, entered, and exited
events. TheMouseMotionListener interface handles mouse dragged and moved events.
36
Example: Moving Message Using Mouse
37
Example: Moving Message Using Mouse
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
38
Example: Moving Message Using Mouse
// Inner class: MovableMessagePanel draws a message
static class MovableMessagePanel extends JPanel {
private String message = "Welcome to Java";
private int x = 20;
private int y = 20;
/** Construct a panel to draw string s */
public MovableMessagePanel(String s) {
message = s;
addMouseMotionListener(new MouseMotionListener() {
@Override /** Handle mouse-dragged event */
public void mouseDragged(MouseEvent e) {
// Get the new location and repaint the screen
x = e.getX();
y = e.getY();
repaint();
}
@Override /** Handle mouse-moved event */
public void mouseMoved(MouseEvent e) {
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, x, y);
}
}
}
39
Code Description
• The MovableMessagePanel class extends JPanel
to draw a message.
• Additionally, it handles redisplaying the message
when the mouse is dragged.
• This class is defined as an inner class inside the
main class because it is used only in this class.
• Furthermore, the inner class is defined as static
because it does not reference any instance
members of the main class.
• The MouseMotionListener interface contains two
handlers, mouseMoved and mouseDragged, for
handling mouse-motion events. 40
Code Description
• When you move the mouse with a button pressed, the
mouseDragged method is invoked to repaint the viewing area
and display the message at the mouse point. When you move
the mouse without pressing a button, the mouseMoved method
is invoked.
• Because the listener is interested only in the mouse-dragged
event, the mouseDragged method is implemented.
• The mouseDragged method is invoked when you move the
mouse with a button pressed.
• This method obtains the mouse location using the getX and
getY methods in the MouseEvent class. This becomes the new
location for the message. Invoking the repaint() method causes
paintComponent to be invoked, which displays the message in
a new location.
41
Key Events
• A key event is fired whenever a key is pressed,
released, or typed on a component.
42
Handling Keyboard Events
To process a keyboard event, use the following
handlers in the KeyListener interface:
• keyPressed(KeyEvent e)
Called when a key is pressed.
• keyReleased(KeyEvent e)
Called when a key is released.
• keyTyped(KeyEvent e)
Called when a key is pressed and then released.
43
The KeyEvent Class
• Methods:
getKeyChar() method
getKeyCode() method
• Keys:
Home VK_HOME
End VK_END
Page Up VK_PGUP
Page Down VK_PGDN
etc...
44
The KeyEvent Class, cont.
45
The End
46