CPSC 2150 - DAY 20 NOVEMBER 10, 2016 ================================================================================ GUI AND THE OBSERVER PATTERN ---------------------------- .A Java program with a GUI, or graphical user interface is pretty routine in most respects .Event - any computer interaction .The widget the user has manipulated is called the subject of the interaction .The objects in your program that need to do something in response to the events for a particular subject are called observers (or listeners) for that subject. SOLUTION 1: USE POLLING ----------------------- .The main program continually polls the subject to see if it has experienced an event. SOLUTION 2: USE CALLBACKS ------------------------- .Each observer (there may be many) registers its interest in subject's events and then waits until the subject calls it back to tell it that there has been an event. .Subject calls the observer when an event happens. .Each subject keeps track of it's own set of interested observers .Whenever an event occurs, the subject invokes a specific callback method for each registered observer, passing an event argument that describes the event. .Each subject expects each observer to register itself with that subject if it is interested in the subject's events. .An example of object oriented design patterns and is considered best practice. Components from Java's Swing Framework +------+ +---------+ |JFRAME| |Action | | | |Listener | +------+ +---------+ ^ ^ extends | / implements +------+ / |Demo | |GUI | +------+ JFRAME +---------------------------------------------------------------+ | || | JTEXTAREA JSCROLLBAR > || | || +---------------------------------------------------------------+ JPANEL | JBUTTON | JBUTTON | | | | +-------------------------------+-------------------------------+ | | | JTEXTAREA | | | +---------------------------------------------------------------+ Multiple threads involved during GUI program execution THREADS ------- .A standard Java program executes in a thread, i.e. a single path of sequential code executing one step at a time. .A GUI program uses at least two threads. TIMELINE OF THREAD EXECUTION ---------------------------- DEMO GUI }-------- SWING } ---- CODE ----------------------------------------> TIME