6.005 17. Event-Based Programming
MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. h JButton JButton JButton Thumbnail Thumbnail Thumbnail Thumbnail Today’s lecture Composite pattern ¾Example: view hierarchy in GUIs Event-based programming ¾Ele:dlingi in graphihicalluseriinterfExampliinput handlifaces Model-view-controller pattern ¾Found throughout user interfaces Event-Based Programming Rob Miller Fall 2008 © Robert Miller 2008 © Robert Miller 2008 Graphical User Interfaces View Hierarchy GUIs are composed from small reusable pieces A GUI is structured as a hierarchy of views ¾A view is an object that displays itself on a rectangular region of the screen JFrame JSplitPane JPanel JScrollPane window (JFrame) button (JButton) tree widget (JTree) © Robert Miller 2008 splitter bar (JSplitPane) scrolling pane (JSplitPane) S ll © Robert Miller 2008 JPanel JScrollPane JPanel Thumbnail JButton JTree JP l 1 Thumbnail Thumbnail JButton JButton JButton Thumbnail Thumbnail Thumbnail Thumbnail l deleteAlbum: MouseListener not to be confused with observer methods in a datatype Composite Pattern View hierarchy is an example of the Composite pattern ¾Primitive views don’t contain other views • button, tree widget, textbox, thumbnail, etc. ¾Composite views are used for grouping or modifying other views• JSplitPane displays two views side-by-side with an adjustable splitter • JScrollPane displays only part of a view, with adjustable scrollbars Key idea ¾primitives and composites implement a common interface (JComponent) ¾containers can hold any JComponent, so both primitives and other containers How the View Hierarchy Is Used Output ¾GUIs change their output by mutating the view hierarchy • e.g., to show a new set of photos, the current Thumbnails are removed from the tree and a new set of Thumbnails is added in their place¾A redraw algorithm automatically redraws the affected views using the interpreter pattern (paint() method) Input ¾GUIs receive keyboard and mouse input by attaching listeners to views (more on this in a bit) Layout JScrollPane JTree ¾An automatic layout algorithm automatically calculates positions and sizes of views using the interpreter pattern (doLayout() method) • Specialized composites (JSplitPane, JScrollPane) do layout themselves • Generic composites (JPanel, JFrame) delegate layout decisions to a layout manager (e.g. FlowLayout,GridLayout,BorderLayout,...) © Robert Miller 2008 JScrollPane JPanel Thumbnail © Robert Miller 2008 Handling Mouse Input Centralized approach? while (true) { read mouse click if (clicked on New Album) doNewAlbum(); else if (clicked on Delete Album) doDeleteAlbum(); else if (clicked on Add Photos) doAddPhotos(); ... else if (clicked on an album in the tree) doSelectAlbum(); else if (clicked on +/-button in the tree) doToggleTreeExpansion(); .... else if (clicked on a thumbnail) doToggleThumbnailSelection(); ... Not modular! ¾Mixes up responsibilities for button panel, album tree, and thumbnails all in one place © Robert Miller 2008 Input Handling on the View Hierarchy Input handlers are associated with views ¾Also called listeners, event handlers, subscribers, and observers JFrame JSplitPane JPanel JScrollPane JPanel JPanel JScrollPane selectThumbnail: MouseListener © Robert Miller 2008 JTree JButton Thumbnai newAlbum: MouseListener selectAlbum: MouseListener not to be confused with observer methods in a datatype 2 – Event-Based Programming Control flow through a graphical user interface ¾A top-level event loop reads input from mouse and keyboard ¾For each input event, it finds the right view in the hierarchy (by looking at the x,y position of the mouse) and sends the event to that views listeners view’s ¾Listener does its thing (e.g. modifying the view hierarchy) and returns immediately to the event loop © Robert Miller 2008 Publish-Subscribe Pattern GUI input handling is an example of the Publish-Subscribe pattern ¾aka Listener, Event, Observer An event source generates a stream of discrete events ¾In this example, the mouse is the event source ¾Events are state transitions in the source ¾Events often include additional info about the transition (e.g. x,y position of mouse), bundled into an event object or passed as parameters Listeners register interest in events from the source ¾Can often register only for specific events e g e.g., only want mouse events occurring inside a view’s bounds ¾Listeners can unsubscribe when they no longer want events When an event occurs, event source distributes it to all interested listeners © Robert Miller 2008 A Closer Look at Listeners JComponent Listener interface MouseListener { void mousePressed(MouseEvent e); id Rl d(M E )void mouseReleased(MouseEvent e); void mouseMoved(MouseEvent e); ... } class JComponent { ... public void addMouseListener(MouseListener l) ... public void removeMouseListener(MouseListener l) ... private void fireMousePress(int x, int y) { MouseEvent event = new MouseEvent(..., x, y, ...); for (MouseListener l : listeners) { l.mousePressed(e); } } Component is very weakly coupled to its listeners ¾Component doesn’t depend on the identity of the listening class, only that it implements the MouseListener interface ¾Component doesn’t depend on the number of listeners, and listeners can come and go © Robert Miller 2008 Other Examples of Publish-Subscribe Higher-level GUI input events ¾JButton sends an action event when it is pressed (whether by the mouse or by the keyboard) ¾JTree sends a selection event when the selected element changes (whether by mouse or by keyboard) ¾JTextbox sends change events when the text inside it changes for any reason Internet messaging ¾Email mailing lists ¾IM chatrooms © Robert Miller 2008 3 the system datan o ati c i ppl a es stor Model ¾ Separating Frontend from Backend We’ve seen how to separate input and output in GUIs ¾Output is represented by the view hierarchy¾Input is handled by listeners attached to viewsMissing piece is the backend of system ¾Backend (aka model) represents the actual data that the user interface is showing and editing ¾Why do we want to separate this from the user interface? Model-View-Controller Pattern Model-View-Controller (MVC) separates responsibilities ¾View displays output¾Controller handles input¾Model stores application data © Robert Miller 2008 A More Detailed Look MVC with a Mutable Model Listener interface decouples the view from the Controller mutates the model; model updates the viewcontroller (somewhat)(e etRtF 4 t i l Decoupling the Model from the View More interfaces decouple the view and the model Summary of MVC View handles output Controller handles input • calls observers on the model to display it • listens for input events on the view hierarchy • listens for model changes and updates display • calls mutators on model or view Another MVC Example:Textbox Advantages of Model-View-Controller Separation of responsibilities ¾Each module is responsible for just one feature • Model: data • View: output • Ctl i Contro er: nput Decoupling ¾View and model are decoupled from each other, so they can be changedindependently ¾Model can be reused with other views • e.g. JTree view that displays the full filesystem tree, and a JLabel viewthat just displays the number of files¾Multiple views can simultaneously share the same model¾Views can be reused with other models, as long as the model implements an interface • e.g. JTree class (the view) and TreeModel interface © Robert Miller 2008 5 11/7/20086 Risks of Event-Based ProgrammingSpaghetti of event handlersControl flow through an event-based program is not simpleYou can’t follow the control just by studying the source code,because control flow depends on listener relationships established at runtimecontrol runtimeCareful discipline about who listens to what (like the model-view-controller pattern) is essential for limiting the complexity of control flowObscured control flow leads to some unexpected pitfalls...© Robert Miller 2008Basic Interaction of Event PassingSequence diagram is good for depicting control flowTime flows downwardEach vertical time line shows one object’s lifetimeHorizontal arrows show calls and returns trading returns, control between objectsDark rectangles show when a method is active (i.e., has been called but hasn’t returned yet)clientsourcelistenerinterface Source {addListeneraddListener()removeListener()observer()mutator()mutatormutator()}changeEventinterface Listener {changeEvent()}© Robert Miller 2008Pitfall #1: Listener Calls ObserversThe listener often calls methods on the sourcee.g., when a textbox gets a change event from its model, it needs to call getText() to get the new text and display itSo observer method calls may occur while the mutator is still in progressprogressobserverclientsourcelistenermutatorchangeEventWhy is this a potential problem?© Robert Miller 2008Pitfall #1: Specific Exampleclass Filesystem {private Map> cache;public List getContents(File folder) {check for folder in cache, otherwise read it from disk and update cache }public void deleteContents(File folder) {for (File f: getContents(folder)) {f.delete();fireChangeEvent(f, REMOVED); //notify listeners that f was deleted }cache.remove(folder); //cache is no longer valid for this folder}}Solutionsource must establish rep invariant before giving up control to any listenersoften done simply by waiting to send events until end of mutator© Robert Miller 200811/7/20087 Pitfall #2: Listener Calls MutatorsThe listener might call mutator on the sourcee.g., when two sources are listening to each other in order to keep their state synchronizedSo calls to mutators may occur while mutator is still in progressprogressmutatorclientsource1listener mutatorchangeEventsource 2listener changeEventmutatorWhy is this a potential problem?© Robert Miller 2008Pitfall #2: Specific ExampleChangeListenerchange eventsetText()JTextboxJSliderChangeListenerChangeListenerchange eventsetValue()Solutiononly send events when mutator actually causes a state change © Robert Miller 2008Pitfall #3: Listener Removes ItselfThe listener might call removeListener() on the sourceThis happens when the listener is done its work, e.g. a listener that executes a stock trade as soon as a certain price is reached So calls to removeListener() may occur while mutator is still in progressprogressremoveListenerclientsourcelistenersetchangeEventWhy is this a potential problem?© Robert Miller 2008Pitfall #3: Specific Exampleclass Source {private Listener[] listeners; private int size;What happens if listeners[i] removes itselfhere?public void removeListener(Listener l) { for (int i = 0; i < size; ++i) {if (listeners[i] == l) { listeners[i] = listeners[size-1]; --size; } }private void fireChangeEvent(...) {for (int i = 0; i < size; ++i) listeners[i].changed(...); } }Java collections (Set, List, etc) have the same problem:itself here? It’s not safe to mutate a collection while you’re iterating over itSolutionfire events by iterating over a copyof the listeners data structureor use javax.swing.EventListenerList which copies only when necessary© Robert Miller 2008Summary View hierarchy ¾Organizes the screen into a tree of nested rectangles ¾Used for dispatching input as well as displaying output ¾windows, panels) can be Uses the Composite pattern: compound views (windows treated just like primitive views (buttons, labels) Publish-subscribe pattern ¾An event source sends a stream of events to registered listeners ¾Decouples the source from the identity of the listeners ¾Beware of pitfalls MVC pattern ¾Separation of responsibilities: model=data, view=output, controller=input ¾Decouples view from model © Robert Miller 2008 8
Description
In this class we will discuss about 1. Fundamentals of programming graphical user interfaces 2.View hierarchy, Composite pattern, Publish-Subscribe pattern, Model-View-Controller (MVC) 3. Pitfalls of event-based programming.A GUI is structured as a hierarchy of views. GUIs are composed from small reusable pieces.
Instructors: Prof. Daniel Jackson, Prof. Robert Miller MIT Course Number: 6.005 Level: Undergraduate, 6.005 17. Event-based programming, Elements of Software Construction, Electrical Engineering and Computer Science, Engineering, Massachusetts Institute of Technology: MIT Open Course Ware, http://ocw.mit.edu (01-11-2011). License: Creative Commons BY-NC-SA: http://ocw.mit.edu/terms/#cc.
Presentation Transcript
Your Facebook Friends on WizIQ