The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA

Slides:



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

***** SWTJC STEM ***** Chapter 4-1 cg 42 Object Oriented Program Terms Up until now we have focused on application programs written in procedural oriented.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
13-Jun-15 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
29-Jun-15 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
Object-Oriented Analysis and Design
14-Jul-15 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
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.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Io package as Java’s basic I/O system continue’d.
Observer Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
GUI programming Graphical user interface-based programming.
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.
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Object-Oriented Programming (Java), Unit 18 Kirk Scott 1.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
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.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
 GUI – Graphic User Interface  Up to now in the programs we have written all output has been sent to the standard output device i.e.: the DOS console.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
CS 4244: Internet Programming User Interface Programming in Java 1.0.
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
6-Jan-16 Model-View-Controller. 2 Design Patterns The hard problem in O-O programming is deciding what objects to have, and what their responsibilities.
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.
Creating a GUI Class An example of class design using inheritance and interfaces.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
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.
21-Jun-16 Swing Basics and Model-View- Controller.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
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.
Java Applet What is a Java Applet? How is applet compiled?
A First Look at GUI Applications
GUIs Model/View/Controller Layouts
Ellen Walker Hiram College
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
A simple example of program design
Introduction to Event Handling
Java IO and Testing made simple
Steps to Creating a GUI Interface
Constructors, GUI’s(Using Swing) and ActionListner
Component-Based Software Engineering
CiS 260: App Dev I Chapter 6: GUI and OOD.
Presentation transcript:

The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA

OK, you’ve got “Hello World” running... What now?

Assignment: Write a program that displays the volume and the surface area for a sphere with the radius entered by the user. A question: How do I enter data in a Java program?

The College Board: “The AP Java subset gives instructors flexibility in how they use Java in their courses. For example, some courses teach how to perform input/output using streams or readers/writers, others teach graphical user interface construction, and yet others rely on a tool or library that handles input/output. For the purpose of the AP Computer Science Exam, these choices are incidental and are not central for the mastery of computer science concepts. The AP Java subset does not address handling of user input at all.”

OK, let’s give it a try: class Sphere { public static void main(String[] args) { EasyReader console = new EasyReader(); System.out.print("Enter the radius: "); double radius = console.readDouble(); System.out.println("Radius = " + radius); double volume = 4.0 / 3.0 * Math.PI * radius * radius * radius; System.out.println("Volume = " + volume); double area = 4.0 * Math.PI * radius * radius; System.out.println("Surface area = " + area); }

What can we learn from this?  Formulas for the volume and surface area of a sphere   The EasyReader class is available for reading console input ( EasyReader is our class, posted at:  Hardly anything about structured programming, Java, or OOP 

What’s wrong with this program?  This is bad design: user interface is interspersed with calculations. In any programming language, user interface should be always separate from calculations or processing  Minor point: the output is ugly (too many digits) 

Second try: import java.text.DecimalFormat; class Sphere { private static double volume(double r) { return 4.0 / 3.0 * Math.PI * r * r * r; } private static double surfaceArea(double r) { return 4.0 * Math.PI * r * r; } Continued 

Sphere (cont’d): public static void main(String[] args) { EasyReader console = new EasyReader(); System.out.print("Enter the radius: "); double radius = console.readDouble(); DecimalFormat f3 = new DecimalFormat("0.000"); System.out.println(); System.out.println("Radius = " + f3.format(radius)); System.out.println("Volume = " + f3.format(volume(radius))); System.out.println("Surface area = " + f3.format(surfaceArea(radius))); System.out.println(); }

So far, so good...  The output looks better  Passable for procedural programming style... But...

 The calculations are bunched together with the user interface (UI) in the same class  It will be hard to reuse the same formulas “methods”) with a different UI... this is not OOP:

 Each object must have its own responsibilities: one is a model of a sphere, another implements UI  We should be able to work as a team, each of us working on different classes In OOP...

Solution: put the “model” and the UI into separate classes.

class Sphere { private double myRadius; private double myCenterX; private double myCenterY; // Constructors: public Sphere (double x, double y, double r) { myCenterX = x; myCenterY = y; myRadius = r; } //... other constructors Continued  private fields (data members)

Sphere (cont’d) // Accessors: public double getRadius() { return myRadius; } //... other accessors // Modifiers: public void setRadius(double r) { myRadius = r; } //... other modifiers Continued 

Sphere (cont’d) public double volume() { return 4.0 / 3.0 * Math.PI * myRadius * myRadius * myRadius; } public double surfaceArea() { return 4.0 * Math.PI * myRadius * myRadius; } //... Other public and private methods public String toString() { return ”Sphere [Center = (" + myCenterX + ", " + myCenterY + ") Radius = " + myRadius + "]"; } Finally!

TestSphere import java.text.DecimalFormat; class TestSphere { public static void main(String[] args) { EasyReader console = new EasyReader(); System.out.print("Enter the radius: "); double radius = console.readDouble(); DecimalFormat f3 = new DecimalFormat("0.000"); Sphere balloon = new Sphere(0, 0, radius); Continued 

TestSphere(cont’d) System.out.println(); System.out.println(balloon); System.out.println("Volume = " + f3.format(balloon.volume())); System.out.println("Surface area = " + f3.format(balloon.surfaceArea())); System.out.println(); }

Reasonable OOP design, but where’s the GUI?

We want something like this:

Let’s make it a team effort  You — a student — write the “model” from the given specs: class Sphere { public Sphere (double x, double y, double r)... public double getRadius()... public void setRadius(double r)... public double volume()... public double surfaceArea()... public String toString()... etc. }

Team effort...  I — the teacher — write the GUI (Even better if my textbook supplies it! ) import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.text.DecimalFormat; public class SphereWindow extends JFrame implements ActionListener { private JTextField radiusIn, volumeOut, areaOut; private Sphere balloon; private DecimalFormat f3 = new DecimalFormat("0.000"); public SphereWindow() { super("Spheres: Volume and Surface"); JPanel view = new JPanel(); view.setLayout(new GridLayout(3, 2, 10, 10)); view.setBorder(new EmptyBorder(10, 10, 10, 10)); view.add(new JLabel("Radius = ", SwingConstants.RIGHT)); radiusIn = new JTextField(8); radiusIn.setBackground(Color.yellow);... continued

My GUI class SphereWindow  It is pretty straightforward but verbose  It uses Java’s event-handling model  If you are a bright, inquisitive student, it will give you a Swing GUI example that you can use in other projects  Do you really want to see it?

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.text.DecimalFormat; public class SphereWindow extends JFrame implements ActionListener { private JTextField radiusIn, volumeOut, areaOut; private Sphere balloon; private DecimalFormat f3 = new DecimalFormat("0.000"); Continued  My GUI class SphereWindow

public SphereWindow() { super("Spheres: volume and surface area"); JPanel view = new JPanel(); view.setLayout(new GridLayout(6, 2, 10, 10)); view.setBorder(new EmptyBorder(10, 10, 10, 10)); view.add(new JLabel("Radius = ", SwingConstants.RIGHT)); radiusIn = new JTextField(8); radiusIn.setBackground(Color.yellow); radiusIn.addActionListener(this); view.add(radiusIn); view.add(new JLabel("Volume = ", SwingConstants.RIGHT));......etc. Full code at SphereWindow (cont’d)

What can we learn from this?  OOP design with a separate model ( Sphere ) and view ( SphereWindow )  Implementing a properly encapsulated, reusable class ( Sphere )  Team development  Elements of Swing — by “immersion” (only if you are so inclined!)

Good job!  Good OOP style  The model and view are separate Now, for “extra credit...”

The Model-View-Controller (MVC) “design pattern”

Design Patterns  OOP design is not easy  Design patterns offer standard ideas for laying out classes  MVC is a commonly used design pattern for implementing interactions between “model,” “view,” and “controller” classes

MVC — the general idea  The controller is an object that processes user commands and program events  The controller (or the “main” class) creates the model  The controller creates a “view” object (or several views) and attaches it (or them) to the model  The controller changes the state of the model  When the model’s state changes, the model updates all the “views” attached to it

Our “Sphere” example now has three classes:  Sphere.java (model)64 lines  TextView.java (view)55 lines  SphereWindow.java (controller/main)40 lines

Hmm... We started with only one class, 16 lines... Now we are like real pros! (MVC and all...)

Java supports MVC with its Observable library class and Observer interface  A “model” class extends Observable, which provides methods for attaching observers and notifying them when a change occurs  A “view” class implements Observer and must supply the update method, called automatically when the model changes

MVC implemented:  The only changes in the Sphere class: import java.util.Observable; class Sphere extends Observable {... public void setRadius(double r) { myRadius = r; setChanged(); notifyObservers(); }... }

MVC implemented (cont’d)  SphereWindow, the “main” class, works as controller, creates the model and the view: public class SphereWindow extends JFrame implements ActionListener { public SphereWindow() { super("Spheres: volume and surface area"); Sphere model = new Sphere(0, 0, 100); TextView view = new TextView(); model.addObserver(view);... } public static void main(...

MVC implemented (cont’d)  Here the main class also acts as the controller and processes GUI events: public class SphereWindow extends JFrame implements ActionListener {... public void actionPerformed(ActionEvent e) { JTextField t = (JTextField)e.getSource(); double r = Double.parseDouble(t.getText()); model.setRadius(r); }...

MVC implemented (cont’d)  The “view” object sets up the display: public class TextView extends JPanel implements Observer { private JTextField radiusIn, volumeOut, areaOut; private DecimalFormat f3 = new DecimalFormat("0.000"); public TextView() { setLayout(new GridLayout(6, 2, 10, 10)); setBorder(new EmptyBorder(10, 10, 10, 10)); add(new JLabel("Radius = ", SwingConstants.RIGHT)); radiusIn = new JTextField(8);...

MVC implemented (cont’d)  The “view” object also updates the display when the model’s state changes: public class TextView extends JPanel implements Observer {... public void update(Observable o, Object arg) { Sphere balloon = (Sphere)o; radiusIn.setText(" " + f3.format(balloon.getRadius())); volumeOut.setText(" " + f3.format(balloon.volume()));... }...

The MVC design pattern adds flexibility:  We can easily implement several views of the same model  We can have several controllers  All views are updated automatically when the model changes  All controllers work independently of each other

One model, two views When the user enters a new radius, both the text and the graphics displays are updated.

One model, two views: public class SphereWindow extends JFrame implements ActionListener { private Sphere model; public SphereWindow() { super("Spheres: volume and surface area"); model = new Sphere(0, 0, 100); TextView tView = new TextView(); model.addObserver(tView); tView.addActionListener(this); tView.update(model, null); GraphicsView gView = new GraphicsView(); model.addObserver(gView); gView.update(model, null);...

One model, two views, two controllers: The user can either enter a new radius or stretch/squeeze the sphere with a mouse — both the text and the graphics displays are updated.

These slides and all the discussed versions of the Sphere code, including the MVC examples, are posted at: questions about the above to me: Other Java resources including EasyReader / EasyWriter are available at: