21
Object-Oriented Object-Oriented Programming with Programming with Java Java The Java Event Model The Java Event Model Lecture 5 Lecture 5

Object-Oriented Programming with Java The Java Event Model Lecture 5

  • View
    221

  • Download
    6

Embed Size (px)

Citation preview

Page 1: Object-Oriented Programming with Java The Java Event Model Lecture 5

Object-Oriented Object-Oriented Programming with JavaProgramming with Java

The Java Event ModelThe Java Event Model

Lecture 5Lecture 5

Page 2: Object-Oriented Programming with Java The Java Event Model Lecture 5

Callbacks and EventsCallbacks and Events

ContentsContents CallbacksCallbacks EventsEvents Events in JavaEvents in Java

Page 3: Object-Oriented Programming with Java The Java Event Model Lecture 5

Pauls Pictures Pauls Documents Pauls Sums Pauls Homework

ProblemsProblems

Pauls Pictures Pauls Documents Pauls Sums Pauls Homework Pauls ToDo Lists

Page 4: Object-Oriented Programming with Java The Java Event Model Lecture 5

My DocumentsReportsPapersPresentations

Client

Window LibraryWindow Library

File SystemCalls

But I need totell you

something!

Slide Shows

I’m in chargehere, guys!

Page 5: Object-Oriented Programming with Java The Java Event Model Lecture 5

CallbacksCallbacks

Callbacks are used in procedural libraries when Callbacks are used in procedural libraries when they need to handle asynchronous eventsthey need to handle asynchronous events

The alternative is for the client to continuously The alternative is for the client to continuously poll the library for eventspoll the library for events This is inefficient, especially if a large number of This is inefficient, especially if a large number of

library components are registered with a clientlibrary components are registered with a client

But the use of callback means a client may But the use of callback means a client may observe “intermediate” states of a libraryobserve “intermediate” states of a library ““Classically” a library’s operations would run to Classically” a library’s operations would run to

completion before returning controlcompletion before returning control

Page 6: Object-Oriented Programming with Java The Java Event Model Lecture 5

Call SequenceCall Sequence

Client aUser Library

Client installs callback

Third party calls library

Library invokes callback“I need to tell you something!”

“What’s happened?”

“He’s changed a name!” Callback queries library

“That’s cool” Callback returns

Library returns

Page 7: Object-Oriented Programming with Java The Java Event Model Lecture 5

Directory ServiceDirectory Service

public class Directory { public void addEntry(String name, File file) { // pre name != “” and file != null // post File file = map.get(name) } public void removeEntry(String name) { // pre name != “” // post map.get(name) = nil } public void registerNotifier(Notifier n) { // pre n != nil // post n registered, will be called on addEntry and removeEntry }}

Page 8: Object-Oriented Programming with Java The Java Event Model Lecture 5

Callbacks and EventsCallbacks and Events

ContentsContents CallbacksCallbacks EventsEvents Events in JavaEvents in Java

Page 9: Object-Oriented Programming with Java The Java Event Model Lecture 5

EventsEvents

An abstraction of Callback that is An abstraction of Callback that is applicable to “federations” of interacting applicable to “federations” of interacting componentscomponents

The firing of an event is a way of one The firing of an event is a way of one object telling one or more other recipients object telling one or more other recipients that something interesting has happenedthat something interesting has happened The sender The sender firesfires an event an event A recipient is called a A recipient is called a listenerlistener and and handleshandles the the

eventevent

Page 10: Object-Oriented Programming with Java The Java Event Model Lecture 5

Java Event ModelJava Event Model

Event SourceEvent Source

Event ListenerEvent Listener

Register Event Listener

Fire Event

EventObject

EventObject

Page 11: Object-Oriented Programming with Java The Java Event Model Lecture 5

Event ObjectsEvent Objects

Encapsulates information specific to an Encapsulates information specific to an instance of an eventinstance of an event

E.g. a “mouse click” event may contain:E.g. a “mouse click” event may contain: The position of the mouse pointerThe position of the mouse pointer Which mouse button was clicked (and how Which mouse button was clicked (and how

many times)many times) The event object is passed as a parameter The event object is passed as a parameter

to the event notification methodto the event notification method

Page 12: Object-Oriented Programming with Java The Java Event Model Lecture 5

Event ListenersEvent Listeners

These are objects that need to be notified These are objects that need to be notified when a certain event occurswhen a certain event occurs

Event notifications are made through Event notifications are made through method invocations in the listening objectmethod invocations in the listening object The event object is passed as a parameterThe event object is passed as a parameter The event source must know which listener The event source must know which listener

object(s) to callobject(s) to call This information is contained in an event-This information is contained in an event-

listener interfacelistener interface

Page 13: Object-Oriented Programming with Java The Java Event Model Lecture 5

Event SourcesEvent Sources

Objects that fire eventsObjects that fire events Implement methods that allow listeners to:Implement methods that allow listeners to:

Register their interest in the events they Register their interest in the events they generate;generate;

Unregister their interest in the events they Unregister their interest in the events they generate.generate.

Multicast event deliveryMulticast event delivery enables an event enables an event to be fired to a number of event-listenersto be fired to a number of event-listeners

Page 14: Object-Oriented Programming with Java The Java Event Model Lecture 5

SummarySummary

EventObject

source

getSource()toString()

EventListener

notification(evt)

EventSource

addListener()removeListener()

fires passed to

registers 0..*

invokes notifications in 0..*

Page 15: Object-Oriented Programming with Java The Java Event Model Lecture 5

Callbacks and EventsCallbacks and Events

ContentsContents CallbacksCallbacks EventsEvents Events in JavaEvents in Java

Page 16: Object-Oriented Programming with Java The Java Event Model Lecture 5

Java EventsJava Events

An “Event” encapsulates information about An “Event” encapsulates information about some state change in its sourcesome state change in its source Pressing a buttonPressing a button Entering text in a text fieldEntering text in a text field Moving a slider on a scroll bar, …Moving a slider on a scroll bar, …

Events need not be generated by users:Events need not be generated by users: Expiration of a timerExpiration of a timer Arrival of incoming data, …Arrival of incoming data, …

Page 17: Object-Oriented Programming with Java The Java Event Model Lecture 5

Event SourcesEvent Sources

An event source must:An event source must: Provide methods to enable “listeners” to register and Provide methods to enable “listeners” to register and

unregister interest in its eventsunregister interest in its events Fire the events, of course!Fire the events, of course! ““Send” each event to all listeners who are interested in that Send” each event to all listeners who are interested in that

type of eventtype of event For an event of For an event of TypeType, and listener , and listener e1e1::

public voidpublic voidaddaddTypeTypeListener(Listener(TypeTypeListener Listener e1e1););

public void public void removeremoveTypeTypeListener(Listener(TypeTypeListener Listener

e1e1););

Page 18: Object-Oriented Programming with Java The Java Event Model Lecture 5

ListenersListeners

Have three responsibilities:Have three responsibilities: Register for events of a certain Register for events of a certain TypeType Implement an interface to “receive” events of Implement an interface to “receive” events of

a certain a certain TypeType Unregister if they no longer wish to receive Unregister if they no longer wish to receive

events of events of TypeType

Page 19: Object-Oriented Programming with Java The Java Event Model Lecture 5

EventsEvents

EventObject:EventObject:EventObject(Object EventObject(Object sourcesource))

Object getSource( )Object getSource( )

String toString( )String toString( )

AWTEvent:AWTEvent:AWTEvent(Object AWTEvent(Object sourcesource, ,

int int idid))

int getID( )int getID( )

String toString( )String toString( )

Object

EventObject

AWTEvent

Page 20: Object-Oriented Programming with Java The Java Event Model Lecture 5

Example: Temperature ConverterExample: Temperature Converter

// Event Source// Event SourceconvertTemp = new JButton("Convert..."); convertTemp = new JButton("Convert..."); ……// Listen to events from Convert button.// Listen to events from Convert button.

convertTemp.addActionListener(this);convertTemp.addActionListener(this);…… // Implementation of ActionListener interface.// Implementation of ActionListener interface. public void actionPerformed(ActionEvent event) {public void actionPerformed(ActionEvent event) { // Parse degrees Celsius as a double and convert to // Parse degrees Celsius as a double and convert to

Fahrenheit.Fahrenheit. int tempFahr = (int)((Double.parseDouble(tempCelsius.getText()))int tempFahr = (int)((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32);* 1.8 + 32);

fahrenheitLabel.setText(tempFahr + " Fahrenheit");fahrenheitLabel.setText(tempFahr + " Fahrenheit"); }}

Page 21: Object-Oriented Programming with Java The Java Event Model Lecture 5

SummarySummary

The components of a software product The components of a software product must interact to achieve a goalmust interact to achieve a goal

In general, it is hard to identify a single In general, it is hard to identify a single component that has overall controlcomponent that has overall control

So a general model is for components to So a general model is for components to interact by triggering “Events” that other interact by triggering “Events” that other components register an interest incomponents register an interest in