Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Hwajung Lee.

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

Graphical User Interfaces
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.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 5: Patterns and GUI Programming CPSC 2100 Software Design and Development 1.
Corresponds with Chapter 12
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
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.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object-Oriented Analysis and Design
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Design patterns Observer,Strategi, Composite,Template (Chap 5, 6)
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
Graphics without NGP The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns that are.
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.
1 CENG 217 Object Oriented Design Lecture 5 Doç. Dr. Halûk Gümüşkaya / Computing Engineering.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Design Patterns and Graphical User Interfaces Horstmann ,
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Computer Science 209 Introduction to Design Patterns: Iterator Composite Decorator.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
 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
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
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.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CSC 480 Software Engineering Design With Patterns.
3461 Laying Out Components Interior Design for GUIs.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
Basics of GUI Programming Chapter 11 and Chapter 22.
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.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
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.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Week 8 Building Graphical User Interfaces in Java Steps to create a GUI Swing GUI components Event handling Software Design Pattern Observer, Composite,
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 Object-Oriented Design & Patterns Cay S. Horstmann.
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
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Design Patterns in Swing and AWT
Design Patterns in Swing and AWT
Activity 1 - Chapter 5 -.
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Hwajung Lee

 A pattern is a description of a problem and its solution that you can apply to many programming situation.  Standardized patterns  User defined patterns  Pattern presents proven advice in a standard format.

 The Pattern Concept  ITERATOR Pattern  OBSERVER Pattern  STRATEGY Pattern  ex. Layout Managers  COMPOSITE Pattern  ex. Components, Containers  DECORATOR Pattern  ex. Scroll Bars  How to Recognize Patterns  Putting Patterns to Work

 Example LinkedList list =...; ListIterator iterator = list.listIterator(); while (iterator.hasNext()) { String current = iterator.next();... }  Why does the Java library use an iterator to traverse a linked list?

 If a programmer manipulates the links directly Link currentLink = countries.head; while (currentLink != null) { do something with currentLink.data; currentLink = currentLink.next; }  Thus, this exposes implementation. ▪ Break Encapsulation unnecessarily ▪ Easy to mess up and corrupt the link structure of a linked list

 History: Architectural Patterns by Christopher Alexander  Each pattern has  a short name  a brief description of the context  a lengthy description of the problem  a prescription for the solution

 The ITERATOR pattern teaches how to access the elements of an aggregate object.

 Context 1. An object (which we ’ ll call the aggregate) contains other objects (which we ’ ll call elements). 2. Clients (that is, methods that use the aggregate) need access to the elements. 3. The aggregate should not expose its internal structure. 4. There may be multiple clients that need simultaneous access.

 Solution 1. Define an iterator that fetches one element at a time. 2. Each iterator object needs to keep track of the position of the next element to fetch. 3. If there are several variations of the aggregate and iterator classes, it is best if they implement common interface type. Then the client only needs to know the interface types, not the concrete classes.

 Names in pattern are examples and may differ in each occurrence of pattern.

Name in Design PatternActual Name AggregateList ConcreteAggregateLinkedList IteratorListIterator ConcreteIternatorAn anonymous class that implements the ListIterator interface type createIterator()listIterator() next() isDone()Opposite of hasNext() currentItem()Return value of next()

 Some programs have multiple editable views of the same data.  Example: HTML Editor ▪ WYSIWYG (What you see is what you get) view ▪ A structural view ▪ …  When you edit on of the view, the other updates automatically and instantaneously.

 Model/view/controller architecture  Model ▪ The raw data ▪ Data structure ▪ No visual appearance  Views ▪ Visual representations  Controllers ▪ An object that processes user interaction (using mouse, keyboard, GUI interface, … ) ▪ Each view has a controller.

 When a user types text into one of the windows:  The controller tells the models to insert the text that the user typed.  The model notifies all views of a change in the model.  All views repaint themselves.  During paint, each view asks the models for the current text.  This architecture minimizes the coupling between the model, views, and controllers.

 The OBSERVER pattern teaches how an object can tell other objects about events.  Context 1. An object (which we ’ ll call the subject) is source of events (such as “ my data has changed ” ). 2. One or more objects (called the observer ) want to know when an event occurs.

 Solution 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 observers.

Name in Design PatternActual Name SubjectJButton ObserverActionListener ConcreteObserverThe class that implements the ActionListener interface type attach()addActionListener notify()actionPerformed

 What if we need to specifies pixel position of components when  User interfaces are made up of use interface components  Components are placed in containers  Swing doesn't use hard-coded pixel coordinates for each component.  Advantages: ▪ Can switch between various "look and feel" ▪ Can internationalize strings  Layout manager arranges the components in a container.

 FlowLayout: left to right, start new row when full  BoxLayout: left to right or top to bottom  BorderLayout: 5 areas, Center, North, South, East, West  GridLayout: grid, all components have same size  GridBagLayout: the rows & columns can have different sizes and components can span multiple rows and columns

 Panel  Set layout manager JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3));  Add components for (int i = 0; i < 12; i++) { keyPanel.add(button[i]); } //end for

 Same backend as text-based system  Only Telephone class changes  Buttons for keypad  Text areas for microphone, speaker

 Panel with BorderLayout for speaker JPanel speakerPanel = new JPanel(); speakerPanel.setLayout(new BorderLayout()); speakerPanel.add(new JLabel("Speaker:"), BorderLayout.NORTH); speakerField = new JTextArea(10, 25); speakerPanel.add(speakerField, BorderLayout.CENTER);  Laying out the microphone Component

 Arrange keys in panel with GridLayout: JPanel keyPanel = new JPanel(); keyPanel.setLayout(new GridLayout(4, 3)); for (int i = 0; i < 12; i++) { JButton keyButton = new JButton(...); keyPanel.add(keyButton); keyButton.addActionListener(...); }

 Put speaker, keypads, and microphone panel into content pane  Content pane already has BorderLayout  Ch5/mailgui/Telephone.java Ch5/mailgui/Telephone.java

 Odd-numbered components right aligned  Even-numbered components left aligned  Implement LayoutManager interface type

public interface LayoutManager { Dimension minimumLayoutSize(Container parent); Dimension preferredLayoutSize(Container parent); void layoutContainer(Container parent); void addLayoutComponent(String name, Component comp); void removeLayoutComponent(Component comp); }

 Ch5/layout/FormLayout.java Ch5/layout/FormLayout.java  Ch5/layout/FormLayoutTester.java Ch5/layout/FormLayoutTester.java

 The STRATEGY pattern teaches how to supply variants of an algorithm  Other manifestation: Comparators Comparator comp = new CountryComparatorByName(); Collections.sort(countries, comp);

 The STRATEGY pattern teaches how to supply variants of an algorithm

 Context 1. A class (called context class) can benefit from different variants for an algorithm 2. Clients of the context class sometimes want to supply custom versions of the algorithm  Solution 1. Define an interface type that is an abstraction for the algorithm. We ’ ll call this interface type the strategy. 2. Concrete strategy classes implement the strategy interface type. Each strategy class implements a version of the algorithm. 3. The client supplies a concrete strategy object to the context class. 4. Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object.

Name in Design PatternActual Name ContextContainer StrategyLayoutManager ConcreteStrategyA layout manager such as BolderLayout doWork()A method of the LayoutManager interface type such as layoutContainer

 Containers collect GUI components  Sometimes, want to add a container to another container  Container should be a component  Composite design pattern  Composite method typically invoke component methods  E.g. Container.getPreferredSize invokes getPreferredSize of components

 The COMPOSITE pattern teaches how to combine several objects into an object that has the same behavior as its parts.

 Context 1. Primitive objects can be combined to composite objects 2. Clients treat a composite object as a primitive object  Solution 1. Define an interface type that is an abstraction for the primitive objects 2. Composite object contains a collection of primitive objects 3. Both primitive classes and composite classes implement that 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.

Name in Design PatternActual Name PrimitiveComponent CompositeContainer or a subclass such as JPanel LeafA component that has no children such as JButton or JTextArea method()A method of the Component interface such as getPreferredSize

 Scroll bars can surround component JTextArea area = new JTextArea(10, 25); JScrollPane pane = new JScrollPane(area);  JScrollPane is again a component

 The DECORATOR pattern teaches how to form a class that adds functionality to another class while keeping 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

 Solution 1. Define an interface type that is an abstraction for the component 2. Concrete component classes implement this interface type. 3. Decorator classes also implement 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.

Name in Design PatternActual Name Component ConcreteComponentJTextArea DecoratorJScrollPane method()A method of the Component interface. For example, the paint method paints a part of the decorated component and the scroll bars.

 Look at the intent of the pattern (ex1) COMPOSITE pattern: to group component into a whole (ex2) DECORATOR pattern: to decorate a component (ex3) STRATEGYpattern: to wrap an algorithm into a class.  Remember common uses (e.g. STRATEGY for layout managers)  Not everything that is strategic is an example of STRATEGY pattern  Use context and solution as “litmus test ”

 We can add border to Swing component. Border b = new EtchedBorder() component.setBorder(b);  Is it an example of DECORATOR?

 Component objects can be decorated (visually or behaviorally enhanced)  The decorated object can be used in the same way as the undecorated object  The component class does not want to take on the responsibility of the decoration  There may be an open-ended set of possible decorations PASS FAIL--the component class has setBorder method

 Invoice contains line items  Line item has description, price  Interface type LineItem: ▪ Ch5/invoice/LineItem.java Ch5/invoice/LineItem.java  Product is a concrete class that implements this interface: ▪ Ch5/invoice/Product.java Ch5/invoice/Product.java

 Bundle = set of related items with description+price (ex) stereo system with tuner, amplifier, CD player + speakers  A bundle has line items  A bundle is a line item  Therefore, COMPOSITE pattern Ch5/invoice/Bundle.javaCh5/invoice/Bundle.java (look at getPrice)

 Store may give discount for an item  Discounted item is again an item  DECORATOR pattern Ch5/invoice/DiscountedItem.javaCh5/invoice/DiscountedItem.java (look at getPrice)

 Model/View of the Invoice System  GUI has commands to add items to invoice  GUI displays invoice  Yet, we want to decouple input from display  Display wants to know when invoice is modified  Display doesn't care which command modified invoice  OBSERVER pattern

 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);

 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) { String formattedInvoice = … ; textArea.setText(formattedInvoice); } }; invoice.addChangeListener(listener);

 Accessing Invoice items  Invoice collect line items  Clients need to iterate over line items  Don't want to expose ArrayList  May change (e.g. if storing invoices in database)  ITERATOR pattern

 Use standard Iterator interface type public interface Iterator { boolean hasNext(); E next(); void remove(); }  remove is "optional operation" (see ch. 8) ▪ implement to throw UnsupportedOperationException  implement hasNext/next manually to show inner workings  Ch5/invoice/Invoice.java Ch5/invoice/Invoice.java

 Simple format: dump into text area  May not be good enough OR  Invoice on a Web page?  E.g. HTML tags for display in browser  Want to allow for multiple formatting algorithms  STRATEGY pattern

 ch5/invoice/InvoiceFormatter.java ch5/invoice/InvoiceFormatter.java  ch5/invoice/SimpleFormatter.java ch5/invoice/SimpleFormatter.java  ch5/invoice/Invoice.java ch5/invoice/Invoice.java  ch5/invoice/InvoiceTester.java ch5/invoice/InvoiceTester.java

 The ITERATOR pattern teaches how to access the elements of an aggregate object.

 Context 1. An object (which we ’ ll call the aggregate) contains other objects (which we ’ ll call elements). 2. Clients (that is, methods that use the aggregate) need access to the elements. 3. The aggregate should not expose its internal structure. 4. There may be multiple clients that need simultaneous access.

 Solution 1. Define an iterator that fetches one element at a time. 2. Each iterator object needs to keep track of the position of the next element to fetch. 3. If there are several variations of the aggregate and iterator classes, it is best if they implement common interface type. Then the client only needs to know the interface types, not the concrete classes.

 The OBSERVER pattern teaches how an object can tell other objects about events.  Context 1. An object (which we ’ ll call the subject) is source of events (such as “ my data has changed ” ). 2. One or more objects (called the observer ) want to know when an event occurs.

 Solution 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 observers.

 The STRATEGY pattern teaches how to supply variants of an algorithm

 Context 1. A class (called context class) can benefit from different variants for an algorithm 2. Clients of the context class sometimes want to supply custom versions of the algorithm  Solution 1. Define an interface type that is an abstraction for the algorithm. We ’ ll call this interface type the strategy. 2. Concrete strategy classes implement the strategy interface type. Each strategy class implements a version of the algorithm. 3. The client supplies a concrete strategy object to the context class. 4. Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object.

 The COMPOSITE pattern teaches how to combine several objects into an object that has the same behavior as its parts.

 Context 1. Primitive objects can be combined to composite objects 2. Clients treat a composite object as a primitive object  Solution 1. Define an interface type that is an abstraction for the primitive objects 2. Composite object contains a collection of primitive objects 3. Both primitive classes and composite classes implement that 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.

 The DECORATOR pattern teaches how to form a class that adds functionality to another class while keeping 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

 Solution 1. Define an interface type that is an abstraction for the component 2. Concrete component classes implement this interface type. 3. Decorator classes also implement 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.