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

Slides:



Advertisements
Similar presentations
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Advertisements

1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Introduction to Java 2 Programming
1 Introduction to Computation and Problem Solving Class 24: Case Study: Building a Simple Postfix Calculator Prof. Steven R. Lerman and Dr. V. Judson Harward.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
OLD BUSINESS : Lets talk about the next exam Project proposals – Functional Definitions Go over homework – NEW BUSINESS: Chapter 4 today GUIs Assignment.
Java Graphical User Interface (GUI) using Visual Editor in eclipse CSI 1390 – Java Programming Instructor: Saeid Nourian University.
Graphical User Interfaces
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Drawing in a frame – Java GUI
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
1 CS1110 Lecture 23, 18 Nov 2010 Listening to GUIs Reading for today: Ch , [ Optional: Ch & (interfaces)] For next lecture:
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
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.
Io package as Java’s basic I/O system continue’d.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
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,
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
The Model-View Approach in Teaching Java Maria Litvin Phillips Academy, Andover, MA
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
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.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
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.
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,
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
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.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
GUI- Model-View-Controller
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
Introduction to Event Handling
Inner Classes 29-Nov-18.
Steps to Creating a GUI Interface
Chapter 5 Processing Input with Applets
GUI- Model-View-Controller
Presentation transcript:

The Model-View Approach in Java

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?

OK, let’s give it a try: class Sphere { public static void main(String[] args) { BufferedReader console = new BufferedReader( new StreamReader(System.in)); System.out.print("Enter the radius: "); double radius = Double.parseDouble( console.readLine()); 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   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 BufferedReader( new StreamReader(System.in)); System.out.print("Enter the radius: "); double radius = Double.parseDouble( console.readLine()); 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) { BufferedReader console = new BufferedReader( new StreamReader(System.in)); System.out.print("Enter the radius: "); double radius = Double.parseDouble( console.readLine()); 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...  Another student can write the GUI 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

The 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  The 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 the rest of the story...”

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: