Continuation:%20GUI - PowerPoint PPT Presentation

About This Presentation
Title:

Continuation:%20GUI

Description:

Decide how user interacts with each subtask ... acquaintance. containment. collection. Structural Perspective. Acquaintance structure: association of objects ... – PowerPoint PPT presentation

Number of Views:150
Avg rating:3.0/5.0
Slides: 99
Provided by: martinja
Category:

less

Transcript and Presenter's Notes

Title: Continuation:%20GUI


1
ContinuationGUIs and eventhandlers in
javaSome on design patterns.
  • Lecturer Martin Jagersand
  • Department of Computing Science
  • University of Alberta
  • Notes based on previous courses by
  • Ken Wong, Eleni Stroulia
  • Zach Dodds, Martin Jagersand

2
Today
  • Example GUI application Calculator
  • Some on design patterns and strategies

3
GUI practicalities
  • Divide task into subtasks/abstractions.
  • Decide how user interacts with each subtask
  • Design and implement drawing of GUI components,
    buttons etc.
  • Connecting buttons, sliders etc to code.
  • Eventhandlers

4
Containers
  • Frame
  • top level container (window)
  • Has typical window components such as close
    buttons, possible scroll down menus etc
  • Panel
  • intermediate container
  • Organizes contained components
  • Atomic components
  • Buttons, labels etc.
  • Presents bits of info, allow interactio

5
Layouts
  • Layouts arrange items by specifying the relative
    locations in a pane.
  • Why layouts? Make interfaces flexible to
    different windows, resizing etc.
  • Alternative use absolute positioning of each
    item
  • Tedious for the programmer
  • Inflexible for the user (cant stretch window to
    see more)

6
Layout examples
7
Event handling
  • How to connect graphics to action
  • Handled though interfaces ActionListeners
  • Programmers implement and specialize these for
    their application

8
Event handling
  • Source object e.g. button
  • Target object programmed to react appropriately

9
Case studyCalculator GUI
  • Was assignment 1 a couple of years ago

10
Design idea 1
  • Use several nested panes for structurally
    different components

Jframe
Command history display
Immediate results display
Numeric keypad
Alfa keypad
11
Flexible layout through the layout manager
  • Small
  • Big

12
Structure
  • Abstract into two classes
  • Extend Jframe to set up the window and menu bars
  • Extend Jpanel to set up and arrange the
    calculator buttons and displays

13
JFrame
  • Class JavaCalcFrame extends Jframe
  • //constructor for menu etc
  • // misc events handling, e.g.
  • addWindowListener(new WindowAdapter()
  • public void windowClosing(WindowEvent e)
  • System.exit(0)
  • )
  • //Instantiate main panel
  • Container contentpane getContentPane()
  • CalculatorPanel panel new CalculatorPanel()
  • contentPane.add(panel)

Example of anonymous class implementing listener
14
JPanelCalculator panel
  • class CalculatorPanel extends JPanel
  • implements ActionListener, KeyListener
  • Implements reactive pattern.

15
Hierarchy of panels
  • class CalculatorPanel extends Jpanel
  • setLayout(new BorderLayout())
  • //Component and panel setup
  • JPanel eastPanel new JPanel()
  • eastPanel.setLayout(new BorderLayout())
  • //display
  • display new JTextField(12)
  • display.setHorizontalAlignment(JTextField.
    RIGHT)
  • display.setEditable(false)
  • Color col new Color(255,255,255)
  • display.setBackground(col)
  • display.addKeyListener(this)
  • Font f new Font("MonoSpaced",
    Font.BOLD, 10)
  • display.setText("0")
  • eastPanel.add(display, "North")

16
Hierarchy of panels 2
  • //scroll capability
  • JScrollPane scrollPane new
    JScrollPane(numList)
  • scrollPane.setFont(f)
  • add(scrollPane, "West")
  • scrollPane.addKeyListener(this)
  • //button panels
  • JPanel moreButs new JPanel()
  • moreButs.setLayout(new GridLayout(4, 2))
  • eastPanel.add(moreButs, "West")
  • centerpanel new JPanel()
  • centerpanel.setLayout(new GridLayout(4,
    4))
  • eastPanel.add(centerpanel, "Center")
  • add(eastPanel, ("Center"))

Add history window, alfa and numeric buttons to
intermediate pane
Add intermediate pane
17
Adding atomic items
  • private void addButton(Container c, String s)
  • JButton b new JButton(s)
  • c.add(b)
  • b.addKeyListener(this)
  • b.addActionListener(this)
  • but b

Take care of event handling in same
class (Reactive pattern)
18
Adding atomic items
  • //button panels
  • JPanel moreButs new JPanel()
  • moreButs.setLayout(new GridLayout(4, 2))
  • String moreButtons "C ", "CE", "M",
    "M-", "MR", "MC", SQRT,
  • ""
  • for (i 0 i lt 8 i)
  • addButton(moreButs,
    moreButtonsi)
  • eastPanel.add(moreButs, "West")
  • centerpanel new JPanel()
  • centerpanel.setLayout(new GridLayout(4,
    4))
  • String buttons "789/456x123-0."
  • for (i 0 i lt buttons.length() i)
  • addButton(centerpanel,
    buttons.substring(i, i 1))
  • centerpanel.setFont(f)
  • eastPanel.add(centerpanel, "Center")

19
EventhandlersMouse events
  • //mouse events
  • public void actionPerformed(ActionEvent evt)
  • st evt.getActionCommand()
  • doAction(st)

Required in interface
Call calculation procedure with string of events
20
EventhandlersKey events
  • //Event handlers
  • public void keyAction(KeyEvent e)
  • char c e.getKeyChar()
  • //handy substitutions
  • if (c '') c 'x'
  • else if (c 'p') c ''
  • //enable the Enter keys
  • else if (c '\n' c141)
  • c ''
  • else if (c 'c') c ''
  • st c ""
  • if (c 'q') st SQRT
  • else st c ""
  • doAction(st)

21
Remains
  • Write the method doAction to perform the actual
    calculations based on the string of events.
    (exercise)

22
Resulting interface
23
Lecture 8, Part 2Designing Classes
  • Heuristics and guidelines
  • discovering a design
  • evaluating a design

24
Designing Classes
  • Issues
  • process is iterative
  • introduce classes
  • consider alternative ideas
  • requires good judgement
  • comes with experience

25
Discovering Class Design
  • Inspirations for classes
  • behavioral perspective
  • focus on actions on the system
  • structural perspective
  • focus on relationships among components
  • information perspective
  • focus on the role of information and its
    manipulation

26
Behavioral Perspective
  • Identify actions(what the system does).
  • Reveal objects to perform the actions.
  • Form collaborations of objects for more complex
    actions.

27
Behavioral Perspective
  • Questions to ask
  • What object initiates the action?
  • What objects collaborate in performing the
    action?
  • What objects are altered in performing the
    action?
  • What objects are queried during the action?

28
Behavioral Perspective
  • Categories of objects often associated with
    action
  • actor
  • reactor
  • transformer
  • agent

29
Behavioral Perspective
  • Actor
  • has a specific goal or mission
  • drives the system to achieve the expected result
  • may enforce the sequencing of activities
  • may cope with exceptional conditions

30
Behavioral Perspective
  • Reactor
  • responds to eventsinternal, external, and user
    interface
  • determines the appropriate reaction
  • initiates the response
  • may require state or be stateless
  • e.g., event handler, action listener

31
Behavioral Perspective
  • Transformer
  • alters input data in some way and produces output
  • may be sequenced or pipelined
  • kindsformatter, filters

32
Behavioral Perspective
  • Formatting transformer
  • displayer
  • render data in human-readable form
  • e.g., stream I/O, text layout, etc.
  • marshaller
  • flatten or linearize structured data
  • e.g., converting data to file blocks
  • encoder
  • convert data into a standard format or encrypt
    the data for secure transfer

33
Behavioral Perspective
  • Filtering transformer
  • screens the input data according to some criteria
  • e.g., pattern matching

34
Behavioral Perspective
  • Agent
  • assists other objects in some way
  • relieves other objects of a responsibility
  • hides information
  • kindsmessenger, server, finder, communicator

35
Behavioral Perspective
  • Messenger agent
  • relays information from one part of the system to
    another
  • relieves the sender from the responsibilities of
    locating the receiver, delivering the
    information, etc.

36
Behavioral Perspective
  • Server agent
  • produces and/or consumes data
  • relieves clients from the responsibilities of
    managing the data
  • e.g., database, web, etc.

37
Behavioral Perspective
  • Finder agent
  • locates other objects or data
  • contains knowledge of how and where to search
  • e.g., search engine, tool registry

38
Behavioral Perspective
  • Communicator agent
  • interacts with the user
  • e.g., present a file dialog

39
II Structural Perspective
  • Identify relationships implied by the
    specification(e.g., consists of, uses,
    maintains, etc.).
  • Form relationships among candidate entities
    (classes).

40
Structural Perspective
  • Questions to ask
  • What objects are involved in the relationship?
  • What objects are necessary to sustain the
    relationship?
  • What objects not in the relationship are aware of
    and exploit the relationship?
  • What objects not in the relationship are used by
    the related objects?

41
Structural Perspective
  • Categories of structure
  • acquaintance
  • containment
  • collection

42
Structural Perspective
  • Acquaintance structure
  • association of objects
  • some objects know about one or more of the other
    objects
  • kindssymmetric or asymmetric,persistent or
    transitory,direct or indirect

43
Structural Perspective
  • Containment structure
  • aggregation of parts into a whole
  • contains, consists of, has
  • kindscollaborator, controller

44
Structural Perspective
  • Collaborator containment
  • whole is created by the interaction of its parts
  • e.g., StopWatch

45
Structural Perspective
  • Controller containment
  • controller object may have total control over
    contained objects
  • e.g., boss/worker model
  • boss delegates tasks to workers
  • workers are independent of each other
  • workers are invisible to the client

46
Structural Perspective
  • Collection structure
  • like containment, but collection does not totally
    conceal the grouped objects
  • objects might be shared across collections
  • kindspeer, iteration, coordinator

47
Structural Perspective
  • Peer collection
  • collection object imposes no control and simply
    gives a name to the grouping
  • grouped objects have equal status

48
Structural Perspective
  • Iterator collection
  • collection object provides selection, ordering,
    or traversal over its objects
  • grouped objects may need to support a common
    interface(e.g., Comparable)

49
Structural Perspective
  • Coordinator collection
  • collection object maintains some invariant
    condition among its objects
  • e.g., RadioButton collection

50
III Information Perspective
  • Study the information content and manipulations
    of the system.
  • Distinguish betweendata (info to be processed)
    and state (info used to control processing).

51
Information Perspective
  • Questions to ask
  • What objects are needed to represent the data or
    state?
  • What objects read the data or query the state?
  • What objects write the data or update the state?

52
Information Perspective
  • Categories of data
  • source or sink
  • a sender or receiver of data outside the system
  • e.g., databases, local files, etc.
  • query
  • a description of the data sought from a source
  • e.g., pattern expression, database query
  • result
  • data returned by a source

53
Information Perspective
  • buffer
  • multiple logical data items gathered into one
    physical unit
  • cache
  • an object anticipating the need for data not yet
    requested by the program
  • synchronizer
  • an object used to enforce timing or sequencing of
    read/write access to data

54
Information Perspective
  • Categories of state
  • recorder
  • objects that represent the current state of the
    system
  • scheduler
  • objects that prioritize among available courses
    of action
  • maintainer
  • objects that transition the system from the
    current state to the next state

55
Evaluating Class Design
  • After proposing a class design, we must evaluate
    it and further refine it.
  • For each class, consider

56
Evaluating Class Design
  • Adequacy of the abstraction
  • identity
  • suggestive name
  • clarity
  • description of intent or purpose is brief
  • uniformity
  • operations are at the same level of abstraction

57
Evaluating Class Design
  • Adequacy of responsibilities
  • clear
  • responsibility is easily understood
  • limited
  • no extraneous, obscuring responsibilities that
    might hinder reuse
  • coherent
  • do one thing and do it well
  • complete
  • responsibilities complete capture the abstraction

58
Evaluating Class Design
  • Adequacy of interface
  • naming
  • clear, active verbs for method names
  • symmetry
  • pairing of inverse operations
  • flexibility
  • overloading to provide defaults or handle
    different inputs

59
IV Design Patterns
  • A design pattern provides a practical, proven
    solution to a recurring design problem.

60
Classification
  • Classification
  • creational
  • creating objects
  • structural
  • composing classes
  • behavioral
  • distributing responsibilities among interacting
    classes

61
Classification
  • A creational pattern
  • singleton
  • intentensure a class only has one instance, and
    provide a global point of access to it

62
Classification
  • A structural pattern
  • adapter
  • intentconvert the interface of a class into
    another interface that clients expect

63
Classification
  • A behavioral pattern
  • chain of responsibility
  • intentavoid coupling the sender of a request to
    its receiver by giving more than one object a
    chance to handle the requestchain the receiving
    objects and pass the request along the chain
    until an object handles it

64
ExampleClient server pattern
  • Covered in previous lecture

65
Example 2Composite pattern
  • Compose objects into tree structures to represent
    part-whole hierarchies.
  • Composite lets clients treat individual objects
    and composites of objects uniformly.

66
Composite pattern
67
Composite pattern
  • Known uses
  • user interface toolkits,
  • a compiler,
  • financial portfolios

68
Observer Design Pattern
  • Intent
  • define a one-to-many dependency between objects
    so that when one object changes state, all its
    dependents are notified and updated automatically

69
Observer Design Pattern
  • Also known as
  • dependents
  • publish and subscribe
  • document-view
  • model-view-controller (MVC)

70
Observer Design Pattern
71
Observer Design Pattern
  • Motivation
  • maintain consistency between cooperating objects
  • separate presentation from computation/persistence
  • update multiple views of common data
  • key objectssubject (model) and observer (view)

72
Observer Design Pattern
  • Applicability
  • when an abstraction has two aspects, one
    dependent on the other
  • when a change to one object requires changing
    some number of others
  • when an object should notify other objects
    without assuming what those objects are

73
Observer Design Pattern
  • Structure

74
Observer Design Pattern
  • Participants (4)
  • Subject
  • tracks its observers
  • provides an interface for attaching/detaching
    Observer objects
  • Observer
  • defines an update interface for observers that
    should be notified of changes in a subject

75
Observer Design Pattern
  • ConcreteSubject
  • stores state of interest to ConcreteObserver
    objects
  • sends a notification to its observers when its
    state changes

76
Observer Design Pattern
  • ConcreteObserver
  • maintains a reference to a ConcreteSubject object
  • stores state that should stay consistent with the
    subjects
  • implements the Observer update interface to keep
    its state consistent with the subjects

77
Observer Design Pattern
  • Collaborations

78
Observer Design Pattern
  • Consequences
  • ConcreteSubject does not need to know the
    concrete class of any observer
  • can add observers any time, without modifying the
    classes of the subject or other observers
  • simple update protocol does not specify what
    changed in the subject

79
Observer Design Pattern
  • Implementation
  • mapping subjects to observers
  • where to store the list of observers
  • observing more than one subject
  • update interface must indicate which subject sent
    the notification
  • who triggers the update?
  • in state-changing operations of the subject
  • or by making clients of the subject responsible

80
Observer Design Pattern
  • Sample code
  • in Java, the Subject abstract class becomes the
    java.util.Observable class
  • public class Observable public
    Observable() public void addObserver(
    Observer o ) public void
    deleteObserver( Observer o ) public
    void notifyObservers() public void
    notifyObservers( Object arg )
    public boolean hasChanged() protected
    void clearChanged() protected void
    setChanged()

81
Observer Design Pattern
  • in Java, the Observer abstract class becomes the
    java.util.Observer interface
  • public interface Observer public void
    update( Observable s, Object arg )

82
Observer Design Pattern
  • // file MessageBoard.javaimport
    java.util.public class MessageBoard extends
    Observable private String message
    public String getMessage() return
    message public void changeMessage(
    String message ) this.message
    message setChanged()
    notifyObservers( this.message ) //
    changed flag is turned off after the //
    notifications

83
Observer Design Pattern
  • public static void main( String args )
    MessageBoard board new MessageBoard()
    Student bob new Student() Student
    joe new Student() board.addObserver(
    bob ) board.addObserver( joe )
    board.changeMessage( Submission
    details posted. )

84
Observer Design Pattern
  • // file Student.javaclass Student implements
    Observer public void update( Observable s,
    Object arg ) // do something whenever
    the // message board changes

85
Observer Design Pattern
  • Known uses
  • Smalltalk
  • Microsoft Foundation Classes
  • ET
  • Interviews

86
Description
  • Elements of a design pattern
  • name
  • short, suggestive name
  • intent
  • concise description of problem addressed
  • motivation
  • show that problem is widespread
  • applicability
  • conditions and constraints that must hold

87
Description
  • structure
  • class and object diagrams
  • participants
  • description of each class
  • collaborations
  • important relationships and interactions
  • consequences
  • pros and cons of using the pattern

88
Description
  • implementation
  • implementation issues
  • sample code
  • code in an object-oriented language
  • known uses
  • systems that use this pattern
  • related patterns
  • pointers to useful other patterns

89
(No Transcript)
90
Catalog
  • Creational
  • abstract factory
  • building
  • factory method
  • prototype
  • singleton

91
Catalog
  • Structural
  • adapter
  • bridge
  • composite
  • decorator
  • facade
  • flyweight
  • proxy
  • Behavioral
  • chain of responsibility
  • command
  • interpreter
  • iterator
  • mediator
  • memento
  • observer
  • state
  • strategy
  • template method
  • visitor

92
Guiding Principles
  • Program to an interface, not an implementation.
  • Use interface variables.
  • Favor object composition over class inheritance.
  • Use association and aggregation.

93
Inheritance versus Composition
  • Inheritance
  • white-box reuse
  • compile time
  • more dependency
  • Composition
  • black-box reuse
  • run time
  • less dependency

94
Frameworks
  • A framework is a set of cooperating classes that
    forms a reusable design for software in a
    specific application domain.
  • e.g., graphical editors, compilers

95
Frameworks
  • Aspects
  • application structure
  • commonality and variability
  • design reuse, not only code reuse
  • evolution

96
Frameworks
  • Inversion of control
  • toolkit/library
  • you write the main body of the application
  • you reuse library code by calling it
  • framework
  • you reuse the main body of the application
  • you write custom code or extensions that the
    framework calls

97
Frameworks and Design Patterns
  • Design patterns are more abstract than
    frameworks.
  • Design patterns are smaller architectural
    elements than frameworks.
  • Design patterns are less specialized than
    frameworks.

98
Software Architecture
  • Architectural style
  • patterns of organizing the components and
    connectors of a software system
  • e.g., pipes and filters, layered, event systems,
    interpreters, blackboard, etc.
Write a Comment
User Comments (0)
About PowerShow.com