the model-view approach in teaching java maria litvin phillips academy, andover, ma...

49
The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA [email protected]

Upload: barry-thornton

Post on 01-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

The Model-View Approachin Teaching Java

Maria LitvinPhillips Academy, Andover, MA

[email protected]

Page 2: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

What now?

Page 3: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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?

Page 4: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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.”

Page 5: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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); }}

Page 6: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu
Page 7: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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: http://www.skylit.com/javamethods)

Hardly anything about structured programming, Java, or OOP

Page 8: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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)

Page 9: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 10: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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(); }}

Page 11: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu
Page 12: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

So far, so good...

The output looks better Passable for procedural programming style

... But...

Page 13: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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:

Page 14: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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...

Page 15: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

class TestSphere(ma i n and UI)

c l a s s Sphe r e(model)

Page 16: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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)

Page 17: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Sphere (cont’d) // Accessors: public double getRadius() { return myRadius; }

// ... other accessors

// Modifiers: public void setRadius(double r) { myRadius = r; }

// ... other modifiers

Continued

Page 18: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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!

Page 19: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 20: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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(); }}

Page 21: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu
Page 22: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Reasonable OOP design, but...

... where’s the GUI?

Page 23: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

We want something like this:

Page 24: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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.}

Page 25: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 26: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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?

Page 27: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 28: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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 http://www.skylit.com/oop/

SphereWindow (cont’d)

Page 29: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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!)

Page 30: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Good job!

Good OOP style The model and view are separate

Now, for “extra credit...”

Page 31: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

The Model-View-Controller (MVC)

“design pattern”

Page 32: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 33: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 34: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Controller

Model

View

createsview

attachesview tomodel

updatesview

Page 35: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Our “Sphere” example now has three classes:

Sphere.java (model) 64 lines

TextView.java (view) 55 lines

SphereWindow.java

(controller/main) 40 lines

Page 36: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Hmm...

We started with only one class, 16 lines...

Now we are like real pros! (MVC and all...)

Page 37: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 38: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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(); } ...}

Page 39: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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(...

Page 40: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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); } ...

Page 41: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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); ...

Page 42: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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())); ... } ...

Page 43: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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

Page 44: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

One model, two views

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

Page 45: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

ControllerSphereWindow.java

M odelSphere.java

View 1TextView.java

View 2GraphicsView.java

Page 46: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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); ...

Page 47: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

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.

Page 48: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

Controller 1TextController.java

M odelSphere.java

View 2GraphicsView.java

Controller 2GraphicsController.java

View 1TextView.java

M ainSphereWindow.java

Page 49: The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA mlitvin@andover.edu

These slides and all the discussed versions of the Sphere code, including the MVC examples, are posted at:

http://www.skylit.com/oop/

e-mail questions about the above to me:

[email protected]

Other Java resources including EasyReader / EasyWriter are available at:

http://www.skylit.com/javamethods.html