Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 5: Patterns and GUI Programming CPSC 2100 Software Design and Development 1.

Slides:



Advertisements
Similar presentations
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Containers and Components 1.Containers collect GUI components 2.Sometimes, want to add a container to another container 3.Container should be a component.
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
1 Patterns & GUI Programming Part 2. 2 Creating a Custom Layout Manager Layout manager determines how components are arranged/displayed in a container.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
Spring 2010CS 2251 Design Patterns. Spring 2010CS 2252 What is a Design Pattern? "a general reusable solution to a commonly occurring problem in software.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Object-Oriented Analysis and Design
Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Hwajung Lee.
Design patterns Observer,Strategi, Composite,Template (Chap 5, 6)
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
More OOP Design Patterns
ITEC324 Principle of CS III Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Modified from slides by Dr. Hwajung Lee.
Java Programming Chapter 10 Graphical User Interfaces.
Applets, AWTS CompSci 230 Software Construction.
Design Patterns and Graphical User Interfaces Horstmann ,
Welcome to CIS 083 ! Events CIS 068.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Computer Science 209 Introduction to Design Patterns: Iterator Composite Decorator.
(c) University of Washington08-1 CSC 143 Models and Views Reading: Ch. 18.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
CS 151: Object-Oriented Design October 24 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
GoF: Document Editor Example Rebecca Miller-Webster.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
CSC 480 Software Engineering Design With Patterns.
CS 151: Object-Oriented Design October 15 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
1 CSE 331 Composite Layouts; Decorators slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Introduction to Swing Mr. Crone. What is Swing? a collection of pre-made Java classes used to create a modern graphical user interface.
Chapter 5 Patterns and GUI Programming -Part 1-. Pattern A pattern is a description of a problem and its solution that you can apply to many programming.
Chapter 5 Patterns and GUI Programming -Part 2-. COMPOSITE Pattern Containers and Components Containers collect GUI components Sometimes, want to add.
Chapter 5 Patterns and GUI Programming. Pattern A pattern is a description of a problem and its solution that you can apply to many programming situation.
Chapter 5 Patterns and GUI Programming -Part 2-. STRATEGY Pattern Layout Managers What if we need to specifies pixel position of components when  User.
A Quick Java Swing Tutorial
Pattern and GUI Programming
Graphical User Interfaces
Christopher Budo, Davis Nygren, spencer franks, Luke miller
“Form Ever Follows Function” Louis Henri Sullivan
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Design Patterns in Swing and AWT
Design Patterns in Swing and AWT
Design Patterns A Case Study: Designing a Document Editor
Composite Pattern Context:
Graphical User Interface
Presentation transcript:

Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 5: Patterns and GUI Programming CPSC 2100 Software Design and Development 1

Chapter Topics The Iterators as Patterns. The Pattern Concept. The OBSERVER Pattern. Layout Managers and the STRATEGY Pattern. Components, Containers, and the COMPOSITE Pattern. Scroll Bars and the DECORATOR Pattern. How to Recognize Patterns. Putting Patterns to Work. 2 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Chapter Objective Introduce the concept of Patterns. Explain Patterns with examples from the Swing user interface toolkit, to learn about Patterns and GUI programming at the same time. 3 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

List Iterators LinkedList list =...; ListIterator iterator = list.listIterator(); while (iterator.hasNext()) { String current = iterator.next();... } Why iterators? 4 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Classical List Data Structure Traverse links directly Link currentLink = list.head; while (currentLink != null) { Object current = currentLink.data; currentLink = currentLink.next; } Problems: o Exposes implementation of the links to the users. o Error-prone. 5 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

High-Level View of Data Structures Queue void add(E x) E peek() E remove() int size() Array with random access E get(int i) void set(int i, E x) void add(E x) int size() 6 Figure 1: The Queue Interface Figure 2: The Array Interface CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

List with Cursor Able to add and remove elements in the middle of the linked list. List with a Curser: E getCurrunt() // Get element at cursor void set(E x) // Set element at cursor x E remove() // Remove element at cursor void insert(E x) // Insert x before cursor void reset() // Reset cursor to head void next() // Advance cursor boolean hasNext() // Check if cursor can be advanced 7 Figure 3: A List with a Cursor CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

List with Cursor for (list.reset(); list.hasNext(); list.next()) { Object x = list.get();... } Disadvantage: Only one cursor per list. o cannot compare different list elements. o cannot print the contents of the list for debugging purposes(side effect of moving the curser to the end). Iterator is superior concept. o A list can have any number of iterators attached to it. 8 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

The Pattern Concept 9 History: Architectural Patterns Christopher Alexander (A pattern language: Towns, Building, Construction, Oxford University Press, 1977). Each pattern has o a short name. o a brief description of the context. o a lengthy description of the problem. o a prescription for the solution. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Short Passages Pattern 10 Context o “... long sterile corridors set the scene for everything bad about modern architecture.” Problem o This section contains a lengthy description of the problem of long corridors, with a depressing picture of a long, straight, narrow corridor with closed doors. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Short Passages Pattern 11 Solution o Keep passages short. Make them as much like rooms as possible, with carpets or wood on the floor, furniture, bookshelves, beautiful windows. Make them generous in shape and always give them plenty of light; the best corridors and passages of all are those which have windows along an entire wall. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Patterns Summary Pattern distills a design rule into a simple format. Check weather the pattern is useful to you? o If so, follow the recipe for the solution. Solution succeeded in the past. You will benefit from it as well. 12 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Iterator Pattern Context 1.An object (aggregate) contains other objects (elements). 2.Clients (methods) need access to the element objects. 3.The aggregate object should not expose its internal structure. 4.Multiple clients may want independent (simultaneous) access. 13 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Iterator Pattern Solution 1.Define an iterator that fetches one element at a time. 2.Each iterator object keeps track of the position of the next element. 3.If there are several aggregate/iterator variations, it is best if the aggregate and iterator classes realize common interface types. 14 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Name in Design PatternActual Name (linked lists) Aggregate List ConcreteAggregate LinkedList Iterator ListIterator ConcreteIterator anonymous class implementing ListIterator createIterator() listIterator() next() isDone() opposite of hasNext() currentItem() return value of hasNext() Names differ in each occurrence of pattern Names in pattern are examples.

Model/View/Controller Some programs have multiple editable views. Example: HTML Editor o WYSIWYG view o structure view o source view Editing one view updates the other. Updates seem instantaneous. 15 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Figure 4: WYSIWYG and a Structural View of the Same HTML Page

Model/View/Controller Model: raw data in a data structure, no visual representation. Views: visual representations (table, graph,...). Controllers: user interaction. 16 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Model/View/Controller What happened when a user types text into one of the windows: 1.The controller tells the model to insert the text that the user typed. 2.The model notifies all views of a change in the model. 3.All views repaint themselves. 4.During painting, each view asks the model for the current text. 17 Figure 5: Sequence Diagram Inserting Text into a View CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Observer Pattern Model notifies views when something interesting happens. o Button notifies action listeners when something interesting happens. Views attach themselves to model in order to be notified. o Action listeners attach themselves to button in order to be notified. Generalize: Observers attach themselves to subject. 18 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Observer Pattern Context 1.An object, called the subject, is source of events. 2.One or more observer objects want to be notified when such an event occurs. 19 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Observer Pattern 20 Solution 1.Define an observer interface type. All concrete observers implement it. 2.The subject maintains a collection of observers. 3.The subject supplies methods for attaching and detaching observers. 4.Whenever an event occurs, the subject notifies all observers. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Name in Design PatternActual Name (Swing buttons) Subject JButton Observer ActionListener ConcreteObserver the class that implements the ActionListener interface type attach() addActionListener() notify() actionPerformed()

Layout Managers User interfaces made up of components (buttons, text fields, sliders,...) Components placed in containers (frames) Container needs to arrange components. Swing doesn't use hard-coded pixel coordinates. o Advantages: Can switch "look and feel" Can internationalize strings. Layout manager controls arrangement. 21 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Layout Managers Predefined in Java FlowLayout o left to right, start new row when full. BoxLayout o left to right or top to bottom. BorderLayout o 5 areas, Center, North, South, East, West. GridLayout o grid, all components have same size. GridBagLayout o complex, like HTML table, grid but rows and columns can have different sizes and components can span multiple rows and columns. 22 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Layout Managers 23 Figure 6: Layout Managers CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Layout Managers 24 Figure 7: Layout Management Classes CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Custom Layout Manager Form layout. Odd-numbered components right aligned. Even-numbered components left aligned. Implement LayoutManager interface type. 25 Figure 12: The FormLayout Custom Layout Manager CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Note: Can use GridBagLayout to achieve the same effect.

The LayoutManager Interface Type 26 public interface LayoutManager { void layoutContainer(Container parent); Dimension minimumLayoutSize(Container parent); Dimension preferredLayoutSize(Container parent); void addLayoutComponent(String name, Component comp); void removeLayoutComponent(Component comp); } CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Strategy Pattern Standard layout managers can be used to provide a custom layout manager: 1.Make an object of the layout manager class and give it to the container. 2.When the container needs to execute the layout algorithm, it calls the appropriate methods of the layout manager object. Strategy Design Pattern. 27 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Strategy Pattern Context 1.A class (context class) can benefit from different variants for an algorithm. 2.Clients sometimes want to replace standard algorithms with custom versions. 28 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Strategy Pattern 29 Solution 1.Define an interface type that is an abstraction for the algorithm. 2.Actual strategy classes realize this interface type. 3.Clients can supply strategy objects. 4.Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Name in Design Pattern Actual Name (layout management) ContextContainer StrategyLayoutManager ConcreteStrategya layout manager such as BorderLayout doWork()a method such as layoutContainer

Other manifestation: Comparators Comparator comp = new CountryComparatorByName(); Collections.sort(countries, comp); The comparator object encapsulates the comparison algorithm. By varying the comparator, you can sort by different criteria. 30 Name in Design PatternActual Name (sorting) ContextCollections StrategyComparator ConcreteStrategya class that implements Comparator doWork()compare Strategy Pattern Sorting CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Composite Pattern Telephone example: o Group components into a panel in order to achieve a satisfactory layout. Technical issue: o User interface components are contained in a containers. o JPanel can contain other components  JPanel is a container. o Add the panel to the frame  JPanel is a component. o Can a container itself be a component? Context 1.Primitive objects can be combined to composite objects. 2.Clients treat a composite object as a primitive object. 31 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Composite Pattern Solution 1.Define an interface type that is an abstraction for the primitive objects. 2.Composite object collects primitive objects. 3.Composite and primitive classes implement same interface type. 4.When implementing a method from the interface type, the composite class applies the method to its primitive objects and combines the results. 32 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Name in Design PatternActual Name (AWT components) PrimitiveComponent CompositeContainer Leafa component without children (e.g. Jbutton) method()A method of Component(e.g. getPreferredSize)

Decorator Pattern Decorator Pattern applies whenever a class enhances the functionality of another class while preserving its interface. Context 1.Component objects can be decorated (visually or behaviorally enhanced) 2.The decorated object can be used in the same way as the undecorated object. 3.The component class does not want to take on the responsibility of the decoration. 4.There may be an open-ended set of possible decorations. 33 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Decorator Pattern Solution 1.Define an interface type that is an abstraction for the component. 2.Concrete component classes realize this interface type. 3.Decorator classes also realize this interface type. 4.A decorator object manages the component object that it decorates. 5.When implementing a method from the component interface type, the decorator class applies the method to the decorated component and combines the result with the effect of the decoration. 34 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013 Name in Design PatternActual Name (scroll bars) Component ConcreteComponentJTextArea DecoratorJScrollPane method()A method of Component(e.g. paint)

Scroll Bars Scroll bars can be attached to (decorate) components. JTextArea area = new JTextArea(10, 25); JScrollPane scroller = new JScrollPane(area); 35 Figure 13: Scroll BarsFigure 14: Adding a Scroll Bar to a Text Area CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Streams 36 The Reader class supports basic input operations: reading a single character or an array of characters. FileReader subclass implements these methods, reading characters from a file. o No method for reading a line of input. BufferedReader takes a Reader and adds buffering. InputStreamReader reader = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(reader); Result is another Reader: Decorator pattern. Many other decorators in stream library, e.g. PrintWriter. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Decorator Pattern: Input Streams 37 Name in Design PatternActual Name (input streams) ComponentReader ConcreteComponentInputStreamReader DecoratorBufferedReader method()read The BufferedReader class is a decorator. It takes an arbitrary reader and yields a reader with additional capabilities. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

How to Recognize Patterns 1.Look at the intent of the pattern. o E.g. COMPOSITE has different intent than DECORATOR. 2.Remember common uses (e.g. STRATEGY for layout managers) o Not everything that is strategic is an example of STRATEGY pattern. 3.Use context and solution as "litmus test" 38 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Litmus Test Can add border to Swing component Border b = new EtchedBorder() component.setBorder(b); Undeniably decorative. Is it an example of DECORATOR? 39 Figure 15: Borders Around Panels CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Litmus Test 1.Component objects can be decorated (visually or behaviorally enhanced) PASS 2.The decorated object can be used in the same way as the undecorated object. PASS 3.The component class does not want to take on the responsibility of the decoration. FAIL--the component class has setBorder method 4.There may be an open-ended set of possible decorations 40 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Putting Patterns to Work invoice.jar Invoice contains line items. Line item has a description and a price. Interface type LineItem: LineItem.java Product is a concrete class that implements this interface: Product.java 41 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Bundles Bundle = set of related items with description and price. o E.g. stereo system with tuner, amplifier, CD player and speakers. A bundle has line items. A bundle is a line item. Bundle.javaBundle.java (look at getPrice) 42 Figure 16: A Bundle of Line Items COMPOSITE pattern CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Discounted Items Store may give discount for an item. Discounted item is again an item. DiscountedItem.javaDiscountedItem.java (look at getPrice) Alternative design: add discount to LineItem. 43 Figure 17: The DiscountItem Decorator DECORATOR pattern CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Model/View Separation GUI has commands to add items to invoice. GUI displays invoice. Decouple input from display. Display wants to know when invoice is modified. Display doesn't care which command modified invoice. OBSERVER pattern. 44 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Model/View Separation OBSERVER pattern: 1.Define an observer interface type. Observer classes must implement this interface type. 2.The subject maintains a collection of observer objects. 3.The subject class supplies methods for attaching observers. 4.Whenever an event occurs, the subject notifies all the observers. 45 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Change Listeners Use standard ChangeListener interface type public interface ChangeListener { void stateChanged(ChangeEvent event); } Invoice collects ArrayList of change listeners. When the invoice changes, it notifies all listeners: ChangeEvent event = new ChangeEvent(this); for (ChangeListener listener : listeners) listener.stateChanged(event); 46 Figure 18: Observing the Invoice OBSERVER pattern CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Change Listeners Display adds itself as a change listener to the invoice. Display updates itself when invoice object changes state. final Invoice invoice = new Invoice(); final JTextArea textArea = new JTextArea(20, 40); ChangeListener listener = new ChangeListener() { public void stateChanged(ChangeEvent event) { textArea.setText(...); } }; invoice.addChangeListener(listener); 47 CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Iterating Through Invoice Items 48 Invoice collect line items. Clients need to know the line items inside an invoice. Don't want to expose ArrayList. May change (e.g. if storing invoices in database). ITERATOR pattern. CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Iterators Use standard Iterator interface type public interface Iterator { boolean hasNext(); LineItem next(); void remove(); } remove is "optional operation". implement to throw UnsupportedException Invoice.java 49 Figure 19: Iterating Through the Items in an Invoice ITERATOR pattern CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Formatting Invoices 50 Simple format: dump into text area. o May not be good enough, HTML tags for display in browser. Want to allow for multiple formatting algorithms. STRATEGY pattern Figure 20: The InvoiceTester Program CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

Formatting Invoices InvoiceFormatter.java SimpleFormatter.java InvoiceTester.java 51 Figure 21: Formatting an Invoice STRATEGY pattern CPSC 2100 University of Tennessee at Chattanooga –Fall 2013

End of Chapter 5 52