Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (2 votes)
243 views

2 Event Driven Programming

Event-driven programming involves executing code in response to events rather than in sequential order. When a button is clicked or other user interaction occurs, it triggers an event that calls the appropriate event handler code. Listeners can be registered to handle different types of events using interfaces like ActionListener, MouseListener, and WindowListener. Events are handled via the delegation model where source components maintain lists of registered listeners that are notified when an event occurs.

Uploaded by

mussdimb
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
243 views

2 Event Driven Programming

Event-driven programming involves executing code in response to events rather than in sequential order. When a button is clicked or other user interaction occurs, it triggers an event that calls the appropriate event handler code. Listeners can be registered to handle different types of events using interfaces like ActionListener, MouseListener, and WindowListener. Events are handled via the delegation model where source components maintain lists of registered listeners that are notified when an event occurs.

Uploaded by

mussdimb
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 28

Event-Driven Programming

Procedural vs. Event-Driven


Programming
Procedural programming is executed in procedural order
procedural - of or relating to procedure
procedure - a series of steps followed in a regular definite
order
In event-driven programming, code is executed upon
activation of events
e.g. menu buttons can be selected in any order
2
Taste of Event-Driven
Programming
The example displays three buttons in the frame.
The content pane's background colour changes when a
button is clicked.
3
ButtonTest
Events
An event can be defined as a type of signal to the
program that something has happened
The event is generated by external user actions such as
mouse movements, mouse clicks, and keystrokes, or by
the operating system, such as a timer
4
ColorAction
ActionListener
JButton

actionPerformed
The Delegation Model

5

source: SourceClass

+addXListener(listener: XListener)

listener: ListenerClass
User
Action
Trigger an event
XListener

+handler(event: XEvent)
Register by invoking
source.addXListener(listener);
(a) A generic source component
with a generic listener


source: JButton
+addActionListener(listener: ActionListener)

listener: CustomListenerClass
ActionListener
+actionPerformed(event: ActionEvent)
Register by invoking
source.addActionListener(listener);
(b) A JButton source component
with an ActionListener
Internal Function of a Source
Component

6

source: SourceClass

+addXListener(XListener listener)

(a) Internal function of a generic source object
event: XEvent listener1
listener2

listenern



+handler(
Keep it a list
Invoke
listener1.handler(event)
listener2.handler(event)

listenern.handler(event)
An event is
triggered

source: JButton

+addActionListener(ActionListener listener)

(b) Internal function of a JButton object
event:
ActionEvent
listener1
listener2

listenern



+handler(
Keep it a list
Invoke
listener1.actionPerformed(event)
listener2.actionPerformed(event)

listenern.actionPerformed(event)
An event is
triggered

The Delegation Model: Example

7
JButton okButton = new JButton("OK");
ActionListener listener = new OKListener();
okButton.addActionListener(listener);
Event Classes

8

AWTEvent EventObject
AdjustmentEvent
ComponentEvent
TextEvent
ItemEvent
ActionEvent
InputEvent
WindowEvent
MouseEvent
KeyEvent
ContainerEvent
FocusEvent
PaintEvent
ListSelectionEvent
Event Information
An event object contains whatever properties which
pertain 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
9
Selected User Actions
User Action Source Event Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Window opened, closed, etc Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
10
Selected Event Handlers
Event Class Listener Interface 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)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
11
Inner Class Listeners
A listener class is designed specifically to create a
listener object for a GUI component (e.g., a button)
It will not be shared by other applications.
So, it is appropriate to define the listener class inside the
frame class as an inner class
12
Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an inner
class to make programs simple.
An inner class can reference the data and methods
defined in the outer class in which it nests, so you do
not need to pass the reference of the outer class to the
constructor of the inner class.
13
Inner Classes (cont.)
Inner classes can make programs simple and concise.
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.
14
Inner Classes (cont.)
An inner class can be declared public, protected, or
private subject to the same visibility rules applied to a
member of the class
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
15
Anonymous Inner Classes
Anonymous class is declared and initialized simultaneously.
As anonymous class has no name, it can be used only once.
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().
An anonymous inner class is compiled into a class named
OuterClassName$n.class. For example, if the outer class Test
has two anonymous inner classes, these two classes are
compiled into Test$1.class and Test$2.class.

16
Anonymous Inner Classes cont..
You use them in situations where you need to create a class
for a specific purpose inside another function, e.g., as a
listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a
function so you never refer to them elsewhere, so you
don't need to name them. The compiler just enumerates
them.
They are essentially syntactic sugar, and should generally be
moved elsewhere as they grow bigger
We can just instantiate an anonymous inner class without
actually making a separate class.
Use this technique for "quick and dirty" tasks where making an
entire class feels unnecessary. Having multiple anonymous
inner classes that do exactly the same thing should be
refactored to an actual class, be it an inner class or a
separate class.

Demo Using Anonymous Inner Classes

18
PlafTest
Example: Handling Window Events
Any subclass of the Window class can generate the following
window events: window opened, closing, closed, activated,
deactivated, iconified, and deiconified.
This program creates a frame, listens to the window events, and
displays a message to indicate the occurring event.
19
TestWindowEvent
Using Adapters
To reduce the number of unimplemented listener interface
methods, you can make use of an adapter instead
The easiest way to use an adapter is to use an anonymous
inner class
import java.awt.event.WindowAdapter;
...
addWindowListener(new WindowAdapter() {
public void windowClosing() {
System.exit(0); });
The WindowAdapter class implements all of the
WindowListener methods
20
MouseEvent

21

java.awt.event.MouseEvent
+getButton(): int
+getClickCount(): int
+getPoint(): java.awt.Point
+getX(): int
+getY(): int


Indicates which mouse button has been clicked.
Returns the number of mouse clicks associated with this event.
Returns a Point object containing the x and y coordinates.
Returns the x-coordinate of the mouse point.
Returns the y-coordinate of the mouse point.


java.awt.event.InputEvent
+getWhen(): long
+isAltDown(): boolean
+isControlDown(): boolean
+isMetaDown(): boolean
+isShiftDown(): boolean



Returns the timestamp when this event occurred.
Returns whether or not the Alt modifier is down on this event.
Returns whether or not the Control modifier is down on this event.
Returns whether or not the Meta modifier is down on this event
Returns whether or not the Shift modifier is down on this event.

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.
22
Handling Mouse Events

23

java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void
+mouseReleased(e: MouseEvent): void
+mouseClicked(e: MouseEvent): void
+mouseEntered(e: MouseEvent): void
+mouseExited(e: MouseEvent): void



Invoked when the mouse button has been pressed on the
source component.
Invoked when the mouse button has been released on the
source component.
Invoked when the mouse button has been clicked (pressed and
released) on the source component.
Invoked when the mouse enters the source component.
Invoked when the mouse exits the source component.
java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void
+mouseMoved(e: MouseEvent): void


Invoked when a mouse button is moved with a button pressed.
Invoked when a mouse button is moved without a button
pressed.

Example: Moving Message Using
Mouse

24
MoveMessageDemo
Example: Handling Complex Mouse
Events

25
ScribbleDemo
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.
26
The KeyEvent Class
Methods:
getKeyChar() method
getKeyCode() method
Keys:
Home VK_HOME
End VK_END
Page Up VK_PGUP
Page Down VK_PGDN
etc...
27
Example: Keyboard Events
Demo

28
KeyEventDemo

You might also like