Model-View-Controller (MVC) Structure Previous - Presentation-Model

Similar documents
User Interface Programming OOP/Java Primer. Step 4 Some Final Checkups

Interfețe Grafice cu Utilizatorul (GUI)

Interfețe Grafice cu Utilizatorul (GUI) I

Based on slides by Prof. Burton Ma

MIT AITI Swing Event Model Lecture 17

MVC: Model View Controller

Swing from A to Z Some Simple Components. Preface

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

Introduction. Introduction

SINGLE EVENT HANDLING

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

RAIK 183H Examination 2 Solution. November 11, 2013

H212 Introduction to Software Systems Honors

Graphical User Interfaces (GUIs)

Java Help Files. by Peter Lavin. May 22, 2004

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Swing - JTextField. Adding a text field to the main window (with tooltips and all)

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Chapter 13 Lab Advanced GUI Applications

Window Interfaces Using Swing Objects

RAIK 183H Examination 2 Solution. November 10, 2014

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Examination - December 15, 2003

SampleApp.java. Page 1

Graphical User Interfaces. Comp 152

Window Interfaces Using Swing Objects

Lecture 5: Java Graphics

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

AP CS Unit 11: Graphics and Events

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Measurement of Earthquakes. New Mexico. Supercomputing Challenge. Final Report. April 3, Team #91. Miyamura High School

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

CS415 Human Computer Interaction

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

GUI Forms and Events, Part II

Swing - JLabel. Adding a text (and HTML) labels to a GUI

Graphical User Interfaces

CSIS 10A Assignment 7 SOLUTIONS

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

To gain experience using GUI components and listeners.

CS Exam 1 Review Suggestions

Swing - JButton. Adding buttons to the main window

Programming Language Concepts: Lecture 8

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Swing from A to Z Using Focus in Swing, Part 2. Preface

Java. GUI building with the AWT

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Systems Programming Graphical User Interfaces

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

COMP Assignment #10 (Due: Monday, March 11:30pm)

Original GUIs. IntroGUI 1

CoSc Lab # 5 (The Controller)

Swing/GUI Cheat Sheet

TTTK Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings)

1.00/1.001 Introduction to Computers and Engineering Problem Solving Fall (total 7 pages)

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

RobotPlanning.java Page 1

Agenda. Container and Component

State Application Using MVC

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

First Name: AITI 2004: Exam 2 July 19, 2004

Example: CharCheck. That s It??! What do you imagine happens after main() finishes?

MODEL UPDATES MANIPULATES USER

Lecture 3: Java Graphics & Events

Chapter 1 GUI Applications

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Final Examination Semester 2 / Year 2012

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

JAVA NOTES GRAPHICAL USER INTERFACES

1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Examination - December 15, 2003

Introduction to the JAVA UI classes Advanced HCI IAT351

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

More Swing. CS180 Recitation 12/(04,05)/08

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Dr. Hikmat A. M. AbdelJaber

Using Several Components

First Name: AITI 2004: Exam 2 July 19, 2004

Advanced Java Unit 6: Review of Graphics and Events

Programmierpraktikum

Graphical User Interfaces. Swing. Jose Jesus García Rueda

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

Client-side GUI. A simple Swing-gui for searching for proudcts

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Day before tests of Java Final test. IDM institution of Bandarawela. Project for department of education

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

University of Cape Town Department of Computer Science Computer Science CSC1017F

PART1: Choose the correct answer and write it on the answer sheet:

Transcription:

Model-View-Controller (MVC) Structure Previous - Presentation-Model Here the calculator is organized according the the Model-View- Controller (MVC) pattern. The idea is to separate the user interface (the Presentation in the previous example) into a View (creates the display, calling the Model as necessary to get information), and Controller (responds to user requests, interacts with both the View and Controller as necessary). The literature on MVC leaves room for a number of variations, but they all follow this basic idea. The MVC idea is praised by many, but in practice separating the View and Controller leads to extra complications in a typical Java program, and the Presentation-Model form is often easier. If there are more complex interactions (eg, the Model is asynchronously updated), an Observer pattern (listeners) may be required. An excellent description of MVC is Sun's article Java SE Application Design With MVC. Another description of MVC can be found at the beginning of the tutorial Applying the Model/View/Controller Design Paradigm in VisualAge for Java (note: VisualAge is obsolete, but the MVC presentation is not). Main program The main program initializes everything and ties everything together. 0 // structure/calc-mvc/calcmvc.java -- Calculator in MVC pattern. // Fred Swartz -- December 00 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);

The View This View doesn't know about the Controller, except that it provides methods for registering a Controller's listeners. Other organizations are possible (eg, the Controller's listeners are non-private variables that can be referenced by the View, the View calls the Controller to get listeners, the View calls methods in the Controller to process actions,...). 0 0 0 // structure/calc-mvc/calcview.java - View component // Presentation only. No user actions. // Fred Swartz -- December 00 import java.awt.*; import javax.swing.*; import java.awt.event.*; class CalcView extends JFrame { //... Constants private static final String INITIAL_VALUE = ""; //... Components private JTextField m_userinputtf = new JTextField(); private JTextField m_totaltf = new JTextField(0); private JButton m_multiplybtn = new JButton("Multiply"); private JButton m_clearbtn = new JButton("Clear"); private CalcModel m_model; //======================================================= constructor /** 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();

0 0 0 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); The Controller The controller process the user requests. It is implemented here as an Observer pattern -- the Controller registers listeners that are called when the View detects a user interaction. Based on the user request, the Controller calls methods in the View and Model to accomplish the requested action. 0 // stucture/calc-mvc/calccontroller.java - Controller // Handles user interaction with listeners. // Calls View and Model as needed. // Fred Swartz -- December 00 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; //========================================================== constructor

0 0 0 /** Constructor 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 MultiplyListener /** When a mulitplication is requested. *. Get the user input number from the View. *. Call the model to mulitply by this number. *. Get the result from the Model. *. 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 //////////////////////////////////////////// inner class ClearListener /**. Reset model. *. Reset View. class ClearListener implements ActionListener { public void actionperformed(actionevent e) { m_model.reset(); m_view.reset(); // end inner class ClearListener The Model The model is independent of the user interface. It doesn't know if it's being used from a text-based, graphical, or web interface. This is the same model used in the presentation example. // structure/calc-mvc/calcmodel.java // Fred Swartz - December 00

0 0 0 // 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 /** Constructor CalcModel() { reset(); //==================================================================== reset /** Reset to initial value. public void reset() { m_total = new BigInteger(INITIAL_VALUE); //=============================================================== multiplyby /** Multiply current total by a number. *@param operand Number (as string) to multiply total by. public void multiplyby(string operand) { m_total = m_total.multiply(new BigInteger(operand)); //================================================================= setvalue /** Set the total value. *@param 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(); Fred Swartz 00 Placed in the public domain.