Design Patterns and Graphical User Interfaces Horstmann 5-5.4.1, 5.4.3-5.7.

Slides:



Advertisements
Similar presentations
Graphic User Interfaces Layout Managers Event Handling.
Advertisements

Containers and Components 1.Containers collect GUI components 2.Sometimes, want to add a container to another container 3.Container should be a component.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 5: Patterns and GUI Programming CPSC 2100 Software Design and Development 1.
OOP Design Patterns Chapters Design Patterns The main idea behind design patterns is to extract the high level interactions between objects and.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
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.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Hwajung Lee.
Design patterns Observer,Strategi, Composite,Template (Chap 5, 6)
CPSC150 JavaLynn Lambert CPSC150 Week 12 InheritanceInterfaces.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
ITEC324 Principle of CS III Chapter 5 (Horstmann’s Book) Patterns and GUI Programming Modified from slides by Dr. Hwajung Lee.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington User Interface COMP 112 #30.
Welcome to CIS 083 ! Events CIS 068.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
Interfaces & Polymorphism part 2:
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
Computer Science 209 Introduction to Design Patterns: Iterator Composite Decorator.
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Field Trip #19 Animations with Java By Keith Lynn.
 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
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
GoF: Document Editor Example Rebecca Miller-Webster.
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
More Design Patterns Horstmann ch.10.1,10.4. Design patterns Structural design patterns –Adapter –Composite –Decorator –Proxy Behavioral design patterns.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
CPS 108/ola.1 From XP to javax.swing.* l What parts of embracing change can we embrace in 108?  Evolutionary design, small releases, iterative enhancement.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Graphics in Java Dr. Andrew Wallace PhD BEng(hons) EurIng
CS 151: Object-Oriented Design October 15 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Computer Science 209 GUIs Model/View/Controller Layouts.
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.
CS 151: Object-Oriented Design October 1 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Java Swing, Events Readings: Just Java 2: Chap 19 & 21, or Eckel’s Thinking in Java: Chap 14 Slide credits to CMPUT 301, Department of Computing Science.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
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:
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 4 Interface Types and Polymorphism Part 2.
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
GUIs and Events Rick Mercer.
Graphical User Interfaces
Interface types and Polymorphism
Observer Pattern Context:
A First Look at GUI Applications
Chapter 4 Interface Types and Polymorphism Part 2
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Design Patterns in Swing and AWT
Design Patterns in Swing and AWT
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Presentation transcript:

Design Patterns and Graphical User Interfaces Horstmann ,

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

Design patterns For each design pattern –Prototypical example –Context, problem –Solution, decoupling/interface –UML diagram Patterns –Iterator, observer, strategy, composite, decorator

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

Example: accessing elements in an ArrayList ArrayList filmList = new ArrayList (); filmList.add(”E.T.”); filmList.add(”Gran Torino”); Printing all elements for (String film : filmList) System.out.println(film); Printing all elements using iterator Iterator iter = filmList.iterator(); while (iter.hasNext()) System.out.println(iter.next()); Printing all elements ”manually” for (int i=0; i< filmList.size(); i++) System.out.println(filmList.get(i));

public Class FilmCatalogue { private String[] films = {”Dogville”,”Chinatown”}; public String get(int i) {return films[i];} public int size() {return films.length;} } Uses encapsulation: YES Fully decoupled: NO –Only ”manual” printing of elements in a FilmCatalogue object possible –very inefficient if array representation changed to linked lists Example: Accessing elements in arbitrary container

Better: decoupling with iterator: public class FilmCatalogue implements Iterable { public Iterator iterator() { return new Iterator () { private int position = 0; public boolean hasNext() {return position<films.length;} public String next() { if (hasNext()) return films[position++]; else return null; }... }; }... }

Example: accessing elements in iterable FilmCatalogue FilmCatalogue filmList = new ArrayList (); filmList.add(”E.T.”); filmList.add(”Gran Torino”); FilmCatalogue filmList = new FilmCatalogue(); Printing all elements for (String film : filmList) System.out.println(film); Printing all elements using iterator Iterator iter = filmList.iterator(); while (iter.hasNext()) System.out.println(iter.next()); Printing all elements ”manually” for (int i=0; i< filmList.size(); i++) System.out.println(filmList.get(i));

Iterator Pattern Context An aggregate object contains element objects Clients need access to the element objects The aggregate object should not expose its internal structure Multiple clients may want independent access Solution Define an iterator that fetches one element at a time Each iterator object keeps track of the position of the next element If there are several aggregate/iterator variations, it is best if the aggregate and iterator classes realize common interface types.

Iterator Pattern

Iterable iterator() FilmCatalogue Iterator next() ! hasNext() next() anonymous EXAMPLE

QUIZ Library myLib = new Library(...); for (Book text : myLib) System.out.println(text); Iterator iter = myLib.iterator(); while (iter.hasNext()) System.out.println(iter.next()); Book[] list = myLib.getBooks(); for (int i=0; i< list.length; i++) System.out.println(list[i]); for (Book text : myLib.getBooks()) System.out.println(text); Which of the code pieces obey the iterator pattern in the UML diagram ? 1.None 2.A only 3.B only 4.C only 5.D only 6.Two of A,B,C,D 7.Three of A,B,C,D 8.All of A,B,C,D 9.I don’t know A B C D

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

Model/View/Controller Extra/changed view transparent to content

Model/View/Controller Model: data structure, no visual representation Views: visual representations Controllers: user interaction Views/controllers update model Model tells views that data has changed Views redraw themselves

Model/View/Controller

Button / Listener recall old example helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } );

Observer Pattern Model notifies views when something interesting happens Button notifies action listeners when something interesting happens Views attach themselves to model in order to be notified Action listeners attach themselves to button in order to be notified Generalize: Observers attach themselves to subject

Observer Pattern

JButtonActionListener anonymous addActionListener() actionPerformed()

QUIZ a)MVC: Frame is Model Display Components are Views Buttons are Controllers b)MVC: Model is not visible, but contains a number Display Components are Views Listeners attached to Buttons are Controllers c)Observer: A Button is a Subject A Listener attached to a button is an Observer Which interpretations are reasonable? 1.None 2.a 3.b 4.c 5.a+b 6.a+c 7.b+c 8.a+b+c 9.I dont’t know Display Components Button Components

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

GUI: components and containers 3 button components textfield component label component frame container with 5 components (textfield, 3 buttons, label)

Layout Managers User interfaces made up of components Components placed in containers Container needs to arrange components Swing doesn't use hard-coded pixel coordinates Advantages: –Can switch "look and feel" –Can internationalize strings Layout manager controls arrangement

Layout Managers

Example JPanel decDisplay = new JPanel(); final JTextField digits = new JTextField(“98",15); decDisplay.add(new JLabel("Decimal:")); decDisplay.add(digits); JPanel display = new JPanel(); display.setLayout(new BorderLayout()); display.add(decDisplay, BorderLayout.NORTH); display.add(binDisplay, BorderLayout.SOUTH); JPanel Default : FlowLayout BorderLayout

Example JPanel keyboard = new JPanel(); keyboard.setLayout(new GridLayout(2,2)); keyboard.add(new JButton("0")); keyboard.add(new JButton("inc")); keyboard.add(new JButton("1")); keyboard.add(new JButton("dec")); JFrame f = new JFrame(); f.add(display,BorderLayout.NORTH); f.add(keyboard,BorderLayout.CENTER); GridLayout JFrame Default : BorderLayout

Strategy Pattern Pluggable strategy for layout management Layout manager object responsible for executing concrete strategy Generalizes to Strategy Design Pattern Other manifestation: Comparators Comparator comp = new CountryComparatorByName(); Collections.sort(countries, comp);

Strategy Pattern Context A class can benefit from different variants for an algorithm Clients sometimes want to replace standard algorithms with custom versions Solution Define an interface type that is an abstraction for the algorithm Actual strategy classes realize this interface type. Clients can supply strategy objects Whenever the algorithm needs to be executed, the context class calls the appropriate methods of the strategy object

Strategy Pattern

Collections Compare() anonymous Comparator

Strategy Pattern LayoutManager Container BorderLayout layoutContainer()

QUIZ public class Graph { private Function f = new Logarithm(); public draw() { plot(1,f.evaluate(1)); … } } public class Graph { private Function f; public Graph(Function fun) { f=fun; } public draw() { plot(1,f.evaluate(1)); … } } Which versions of Graph class use strategy pattern? 1. None 2. A 3. B 4. A,B 5.I don’t know A B

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

Containers and Components 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

Composite Pattern Context Primitive objects can be combined to composite objects Clients treat a composite object as a primitive object Solution Define an interface type that is an abstraction for the primitive objects Composite object collects primitive objects Composite and primitive classes implement same interface type. When implementing a method from the interface type, the composite class applies the method to its primitive objects and combines the results

Composite Pattern

Component JPanel JButton getPreferredSize()

QUIZ class Rectangle: public void paint(Graphics2D g) { g.draw(...); } class Composite: private ArrayList cubes; public void paint(Graphics2D g) { for (Rectangle r: cubes) r.paint(g); } Does UML and code for paint methods realize composite design pattern? 1.Yes, both UML and code 2.Only UML 3.Only code 4.Neither UML nor code 5.I don’t know

Design patterns Design Patterns Iterator Model-View-Controller and Observer Strategy Composite Decorator

Scroll Bars Scroll bars can be attached to components Approach #1: Component class can turn on scroll bars Approach #2: Scroll bars can surround component JScrollPane pane = new JScrollPane(component); Swing uses approach #2 JScrollPane is again a component

Decorator Pattern Context 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 Solution Define an interface type that is an abstraction for the component Concrete component classes realize this interface type. Decorator classes also realize this interface type. A decorator object manages the component object that it decorates 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.

Decorator Pattern

JScrollPane JComponent JTextArea paintComponent()

QUIZ class Rectangle: public void paint(Graphics2D g) { g.draw(...); } class Decor: private Cubism cube; public void paint(Graphics2D g) { g.draw(new Rectangle2D(...)); g.draw(... cube...); } Does UML and code for paint methods realize decorator design pattern? 1.Yes, both UML and code 2.Only UML 3.Only code 4.Neither UML nor code 5.I don’t know