2/3/20161. 2 3 Many facts about MVC A design pattern for the architecture of GUI applications. It works to separate data, UI and its control for a more.

Slides:



Advertisements
Similar presentations
The Model-View Approach in Java. OK, you’ve got “Hello World” running... What now?
Advertisements

Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Model-View-Controller Architecture Hector Raphael Mojica.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Graphical User Interface (GUI) Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Overview of Swing’s MVC Architecture By Geoffrey Steffens (BCSi), Socket Software, Australia Copyright © Socket Software, 2002.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Graphical User Interface (GUI) Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Object-Oriented Analysis and Design
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
UNIT-V The MVC architecture and Struts Framework.
MVC pattern and implementation in java
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Model View Controller (MVC) Rick Mercer with a wide variety of others 1.
Software Construction Lecture 10 Frameworks
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
MVC CompSci 230 S Software Construction. MVC Architecture  A typical application includes software to  maintain application data,  document text.
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Software Design 4.1 Tell, Don't Ask l Tell objects what you want them to do, do not ask questions about state, make a decision, then tell them what to.
(c) University of Washington08-1 CSC 143 Models and Views Reading: Ch. 18.
The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA
COMP 6471 Software Design Methodologies Winter 2006 Dr Greg Butler
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
3461 Model-View Controller Advanced GUI concepts.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many others 1.
1 CSC 222: Object-Oriented Programming Spring 2012 netBeans & GUIBuilder  netBeans IDE create/edit/run a project  GUIBuilder JFrame, JButton, JTextField,
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Event Driven Programming. Event-driven Programming In the early days of computing communication with the outside world was accomplished using a technique.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many of others 1.
Swinging in Your Java Playground. Background Swing is a part of the Java Foundation Classes (JFC). The JFC is made up of features intended to give a programmer.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Model View.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Computer Science 209 GUIs Model/View/Controller Layouts.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Model View Controller (MVC) an architecture Rick Mercer with help from many of others 1.
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.
Java - hello world example public class HelloWorld { public static void main (String args[]) { System.out.println("Hello World"); }
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)
View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user interface element (the user interface.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
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:
High degree of user interaction Interactive Systems: Model View Controller Presentation-abstraction-control.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
GUIs Model/View/Controller Layouts
Review: Java GUI Programming
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Graphical User Interfaces -- Introduction
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Model-View-Controller (MVC): Software Architecture Design Pattern
A Quick Java Swing Tutorial
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Model, View, Controller design pattern
Presentation transcript:

2/3/20161

2

3

Many facts about MVC A design pattern for the architecture of GUI applications. It works to separate data, UI and its control for a more cohesive and modularized system. Trygve Reenskaug formulated the MVC pattern for GUI design in 1979 while visiting the Xerox Palo Alto Research Center (PARC). Used in making Apple interfaces (Lisa and Macintosh). First used in the Smalltalk-80 framework. Implementation in Java can be found in Swing. Very popular, used extensively in Java and other languages. 2/3/20164

Model represents data model Manages behavior and data of application domain Classes in the system related to the internal representation of the state of the system often part of the model is connected to file(s) or database(s) examples (card game): Card, Deck, Player examples (bank system): Account, User, UserList MVC – The Model 2/3/20165

Has methods to access and possibly update its contents. Implements an interface which defines the allowed model interactions. An interface enables models to be pulled out and replaced without programming changes. 2/3/20166

View represents the screen(s) shown to the user Manages the graphical and/or textual output to the display associated to its application Classes in the system that display the state of the model to the user GUI (could also be a text UI) should not contain crucial application data examples: PokerPanel, BankApplet MVC – The View 2/3/20167

There can be multiple views displaying the model at any one time. Example, a companies finances over time could be represented as a table and a graph. Example: Bar chart vs. pie chart When the model is updated, all Views are informed and given a chance to update themselves. 2/3/20168

Controller represents interactions from the user that changes the data and the view Interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate Classes that connect model and view defines how UI reacts to user input (events) receives messages from view (where events come from) sends messages to view/model (tells what data to display/update) sometimes part of view MVC – The Controller 2/3/20169

Users interact with the controller. It interprets mouse movement, clicks, keystrokes, etc Communicates those activities to the model – eg: delete row, insert row, etc Interaction with the model indirectly causes the View(s) to update 2/3/201610

How do MVC work together? User interacts with the VIEW UI CONTROLLER handles the user input (often a callback function attached to UI elements) CONTROLLER updates the MODEL and/or UI VIEW uses MODEL to generate new UI UI waits for user interaction 2/3/201611

12 User Input Update model Change in model Update view 2/3/201612

Should view and model interact directly? No, allowing View to directly access Model creates a dependency Yes, on pure MVC, View talks directly with Model and vice-versa. Controller is only used when any change arises. Yes, controller is about user events, not model-to-view communication. In classical MVC, view observes model. Yes/No, MVC is only about separate Model-View- Control 2/3/201613

What are the benefits of MVC? Separation of concerns in the code Developer specialization and focus Parallel development by separate team Makes it very easy to have multiple different displays of the same information (For example: a graph and a table could both display and edit the same data.) have multiple different displays of the same information (For example: a graph and a table could both display and edit the same data.) have different controls of the same view 2/3/201614

Separation of concern Allows re-use of business-logic across applications Allows development of multiple UIs without business logic Allows development of multiple UIs without business logic Discourages “cut-past” repetition of code, streamlining upgrade and maintenance tasks Discourages “cut-past” repetition of code, streamlining upgrade and maintenance tasks 2/3/201615

Developer specialization and focus UI developers can focus exclusive on UI without being bogged down in business logic rules UI developers can focus exclusive on UI without being bogged down in business logic rules Business logic developers can focus on business logic without worrying about UI widgets Business logic developers can focus on business logic without worrying about UI widgets 2/3/201616

Parallel Development teams Business logic developers can build “stub” classes that allow UI developers to forge ahead before business logic is fully implemented Business logic developers can build “stub” classes that allow UI developers to forge ahead before business logic is fully implemented UI can be changed as much as the customer requirements without slowing down the business logic development UI can be changed as much as the customer requirements without slowing down the business logic development Business rule changes are less likely to require revision of the UI Business rule changes are less likely to require revision of the UI 2/3/201617

APIs: The Glue between Model, View, and Controller Separation of concerns mean one layer does not care how another layer is implemented Each layer relies solely on the behaviors specified in the API of other layers The API specifies the behavior of the interface between a layer and the layers that interact with it. The APIs may be considered contracts to which each development team agrees before going off to implement the behavior promised by interface 2/3/201618

A DemoMVC Example 2/3/201619

Main // CalcMVC.java -- Calculator in MVC pattern. import javax.swing.*; public class CalcMVC { //... Create model, view, and controller. They are // created once here and passed to the parts that // need them so there is only one copy of each. public static void main(String[] args) { CalcModel model = new CalcModel(); CalcView view = new CalcView(model); CalcController controller = new CalcController(model, view); view.setVisible(true); } 2/3/201620

Controller // CalcController.java - Controller // Handles user interaction with listeners. // Calls View and Model as needed. import java.awt.event.*; public class CalcController { //... The Controller needs to interact with both the Model and View. private CalcModel m_model; private CalcView m_view; CalcController(CalcModel model, CalcView view) { m_model = model; m_view = view; //... Add listeners to the view. view.addMultiplyListener(new MultiplyListener()); view.addClearListener(new ClearListener()); } //////////////////////////////////inner class ClearListener /** 1. Reset model. * 2. Reset View. */ class ClearListener implements ActionListener { public void actionPerformed(ActionEvent e) { m_model.reset(); m_view.reset(); } }// end inner class ClearListener //////////////////////////////////inner class MultiplyListener /** When a mulitplication is requested. * 1. Get the user input number from the View. * 2. Call the model to mulitply by this number. * 3. Get the result from the Model. * 4. Tell the View to display the result. * If there was an error, tell the View to display it. */ class MultiplyListener implements ActionListener { public void actionPerformed(ActionEvent e) { String userInput = ""; try { userInput = m_view.getUserInput(); m_model.multiplyBy(userInput); m_view.setTotal(m_model.getValue()); } catch (NumberFormatException nfex) { m_view.showError("Bad input: '" + userInput + "'"); } }//end inner class MultiplyListener } 2/3/201621

View // CalcView.java - View component // Presentation only. No user actions. import java.awt.*; import javax.swing.*; import java.awt.event.*; class CalcView extends JFrame { //... Constants private static final String INITIAL_VALUE = "1"; //... Components private JTextField m_userInputTf = new JTextField(5); private JTextField m_totalTf = new JTextField(20); private JButton m_multiplyBtn = new JButton("Multiply"); private JButton m_clearBtn = new JButton("Clear"); private CalcModel m_model; /** Constructor */ CalcView(CalcModel model) { //... Set up the logic m_model = model; m_model.setValue(INITIAL_VALUE); //... Initialize components m_totalTf.setText(m_model.getValue()); m_totalTf.setEditable(false); //... Layout the components. JPanel content = new JPanel(); content.setLayout(new FlowLayout()); content.add(new JLabel("Input")); content.add(m_userInputTf); content.add(m_multiplyBtn); content.add(new JLabel("Total")); content.add(m_totalTf); content.add(m_clearBtn); //... finalize layout this.setContentPane(content); this.pack(); this.setTitle("Simple Calc - MVC"); // The window closing event should probably be passed to the // Controller in a real program, but this is a short example. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void reset() { m_totalTf.setText(INITIAL_VALUE); } String getUserInput() { return m_userInputTf.getText(); } void setTotal(String newTotal) { m_totalTf.setText(newTotal); } void showError(String errMessage) { JOptionPane.showMessageDialog(this, errMessage); } void addMultiplyListener(ActionListener mal) { m_multiplyBtn.addActionListener(mal); } void addClearListener(ActionListener cal) { m_clearBtn.addActionListener(cal); } 2/3/201622

Model // CalcModel.java // Model // This model is completely independent of the user interface. // It could as easily be used by a command line or web interface. import java.math.BigInteger; public class CalcModel { //... Constants private static final String INITIAL_VALUE = "0"; //... Member variable defining state of calculator. private BigInteger m_total; // The total current value state. /** Constructor */ CalcModel() { reset(); } /** Reset to initial value. */ public void reset() { m_total = new BigInteger(INITIAL_VALUE); } /** Multiply current total by a number. operand Number (as string) to multiply total by. */ public void multiplyBy(String operand) { m_total = m_total.multiply(new BigInteger(operand)); } /** Set the total value. value New value that should be used for the calculator total. */ public void setValue(String value) { m_total = new BigInteger(value); } //====================================== getValue /** Return current calculator total. */ public String getValue() { return m_total.toString(); } 2/3/201623

Another DemoMVC Example 2/3/201624

2/3/201625

Source code Model (see printout)printout View (see printout)printout Controller (see printout)printout Main (see printout)printout 2/3/201626

Pattern of Patterns 2/3/201627

2/3/201628

2/3/201629

2/3/201630

2/3/201631

2/3/201632

2/3/201633

2/3/201634

2/3/201635

2/3/201636

2/3/201637

What is software design pattern? The idea of Design Patterns in software engineering grew out of work by Professor Christopher Alexander of UC Berkeley’s architecture department His ideas were applied to Software Engineering by authors of Design Patterns: Elements of Reusable Object-Oriented Software In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. 2/3/201638

Why should programmers care about Design Pattern? It gives developers a common vocabulary to talk about software solutions. Designing applications in explicit conformity to design patterns facilitates the re-use of the insight and experience gleaned by the best and brightest developers over the course of thousands of real-world software development efforts. In short, Design Patterns will make you a better programmer and architect. 2/3/201639

2/3/201640

2/3/201641

2/3/201642