Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.

Similar presentations


Presentation on theme: "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface."— Presentation transcript:

1 An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface and model: the Model-View-Controller pattern

2 1May 2004NH-Chapter 18 Objectives ñAfter studying this chapter you should understand the following: ñthe Model-View-Controller pattern: components and their roles; ñthe observer pattern, as realized by the class Observable and interface Observer, and its use in the MVC pattern. ñAlso, you should be able to: ñwrite a graphical user interface for a simple application using the MVC architecture.

3 2May 2004NH-Chapter 18 Model-View-Controller ñAn Application structure ñmodel components – objects that model and solve problem; ñview components – objects that display model; ñ controller components – objects that handle user input.

4 3May 2004NH-Chapter 18 Model-View-Controller advantages ñProcessing of input and output is separate; ñControllers can be interchanged, allowing different user interaction modes; ñAllows multiple views of model.

5 4May 2004NH-Chapter 18 M-V-C architecture Model Controller control1 Controller control2 View view1 View view2 View view3

6 5May 2004NH-Chapter 18 Observer/Observable relationships ñjava.util provides class Observable, interface Observer. ñObserver is client and Observable is server. ñObserver registers with the Observable, ñObservable informs Observer when it changes state.

7 6May 2004NH-Chapter 18 M-V-C example ñModel: a right triangle. ñbase and height can be modified. ñThree different views of triangle. ñView one displays lengths of sides. ñView two displays triangle graphically. ñView three logs changes in triangle state to file. ñA controller for view one, to modify triangle. ñNo controller for other views.

8 7May 2004NH-Chapter 18 public class RightTriangle { private int base; private int height; private int hypotenuse; public RightTriangle (int base, int height) { this.base = base; this.height = height; setHypotenuse(); } public int base () { return this.base; } public int height () { return this.height; } public int hypotenuse () { return this.hypotenuse; } public void setBase (int newBase) { this.base = newBase; setHypotenuse(); } public void setHeight (int newHeight) { this.height = newHeight; setHypotenuse(); } private void setHypotenuse () { this.hypotenuse = (int) Math.round( Math.sqrt(base*base + height*height)); } }//end RightTriangle. RightTriangle class

9 8May 2004NH-Chapter 18 Observable methods public void addObserver (Observer o); protected void setChanged (); public void notifyObservers (); public void notifyObservers (Object arg); ñjava.util.Observable class specification provides several methods; among those:

10 9May 2004NH-Chapter 18 ñWhen RightTriangle changes state, to notify all registered observers of the event, modifies commands to add: Structuring an Observer/Observable ñRightTriangle extends Observable: public class RightTriangle extends Observable …  All views are Observer’s of RightTriangle instance rt  Client Observer registers to rt invoking addObserver. rt.addObserver(this); setChanged(); notifyObservers();

11 10May 2004NH-Chapter 18 Implementing an Observable  RightTriangle changes state in setBase or setHeight : public void setBase (int newBase) { this.base = newBase; setHypotenuse(); setChanged(); notifyObservers(); } public void setHeight (int newHeight) { this.height = newHeight; setHypotenuse(); setChanged(); notifyObservers(); }

12 11May 2004NH-Chapter 18 Interface Observer interface Observer { void update (Observable o, Object arg); }

13 12May 2004NH-Chapter 18 Observer structure class RTObserver implements Observer { private RightTriangle target; // Create an observer of RightTriangle rt. public RTObserver (RightTriangle rt) { target = rt; target.addObserver(this); … } public void update( (Observable o, Object arg){ do something about o’s state change. } … } observer registers with model ñObserver must know target object. ñObserver registers itself with the target.  When target notifies observer, observer executes update.

14 13May 2004NH-Chapter 18 A simple view and controller for RightTriangle ñBuild a view that shows the three components of the triangle in text fields. ñController will capture input from text fields labeled Base and Height, and modify state of the RightTriangle appropriately.

15 14May 2004NH-Chapter 18 The View ñView extends JPanel and implements Observer. ñRightTriangle to display is provided as constructor argument. class TextView extends JPanel implements Observer { private final static int FIELD_SIZE = 16; private JTextField base; private JTextField height; private JTextField hypotenuse; public TextView (RightTriangle model) { super(); … base = new JTextField(FIELD_SIZE); base.setActionCommand("Base"); … height = new JTextField(FIELD_SIZE); height.setActionCommand("Height"); … hypotenuse = new JTextField(FIELD_SIZE); hypotenuse.setEditable(false); … }

16 15May 2004NH-Chapter 18 The View ñView extends JPanel and implements Observer. ñRightTriangle to display is provided as constructor argument.

17 16May 2004NH-Chapter 18 The View ñWhen model changes state, notifies view to update text fields.  View’s update queries model for new state information, and writes it into text fields: public void update (Observable model, Object arg) { int side; RightTriangle rt = (RightTriangle)model; side = rt.base(); base.setText(String.valueOf(side)); side = rt.height(); height.setText(String.valueOf(side)); side = rt.hypotenuse(); hypotenuse.setText(String.valueOf(side)); }

18 17May 2004NH-Chapter 18 Controller structure  Captures user input from base and height text fields ñmust have references to the text fields, ñmust respond to ActionEvents generated by text fields, ñmust be an ActionListener, ñmust be added as listener to text fields. ñUpdates model. ñThis is response to ActionEvent text fields generate. ñMust have reference to RightTriangle.

19 18May 2004NH-Chapter 18 Controller structure private class TVController implements ActionListener { private RightTriangle model; /** * Create a new controller for this TextView of the * specified RightTriangle. */ public TVController (RightTriangle model) { this.model = model; ¹TextView.this.base.addActionListener(this); TextView.this.height.addActionListener(this); }

20 19May 2004NH-Chapter 18 Controller structure /** * Update the model in response to user input. */ public void actionPerformed (ActionEvent e) { JTextField tf = (JTextField)e.getSource(); try { int i = Integer.parseInt(tf.getText()); if (i < 0) throw new NumberFormatException(); String which = e.getActionCommand(); if (which.equals("Base")) model.setBase(i); else model.setHeight(i); } catch (NumberFormatException ex) { TextView.this.update(model, null); }

21 20May 2004NH-Chapter 18 Model, View and Controller

22 21May 2004NH-Chapter 18 Nim Game : Model Player «interface» IndependentPlayerInteractivePlayer AbstractPlayer GamePile directs provides 2 u s e s

23 22May 2004NH-Chapter 18 Nim Game : TUI

24 23May 2004NH-Chapter 18 Nim Game : TUI v.s. GUI design ñTUI design: ñTUIController ñregisters with InteractivePlayer, ñprompts and reads user’s move, forwards it to InteractivePlayer.  The play loop is in the interface.

25 24May 2004NH-Chapter 18 Nim Game : GUI design

26 25May 2004NH-Chapter 18 Nim Game : TUI v.s. GUI design ñGUI design ñNo explicit loop coded. ñUser repeats some event. ñNimController  W hen user presses an input button it invokes setNumberToTake on InteractivePlayer.  Invokes Game’s play, ñonce for InteractivePlayer, ñonce for IndependentPlayer.

27 26May 2004NH-Chapter 18 View ñDisplay composed of four panels: ña panel to display number of sticks remaining, ñtwo panels each with a text field to report player’s moves, ña panel containing buttons for user to make a move.

28 27May 2004NH-Chapter 18 NimController

29 28May 2004NH-Chapter 18 View ñA NimInterface instance: ñbuilds display, ñobserves the Game.

30 29May 2004NH-Chapter 18 Model’s Game ñWhen Game completes a play, it notifies its Observers. public void play () { if (!gameOver()) { nextPlayer.takeTurn(pile,MAX_ON_A_TURN); previousPlayer = nextPlayer; nextPlayer = otherPlayer(nextPlayer); setChanged(); notifyObservers(); }

31 30May 2004NH-Chapter 18 GUI structure ñUser selects “New Game” from main menu.  Menu item listener invokes NimController’s initializeGame : ñ displays a JDialog to get initialization data from user, ñcreates a Game.

32 31May 2004NH-Chapter 18 NimInterface ñWhen notified, ñ queries Game, ñ updates display. ñNimInterface responsible for ñdisplaying the number of sticks remaining in the game; ñreporting the winner when the game is over.

33 32May 2004NH-Chapter 18 Sub-views ñNimInterface ñdefines an inner class PlayerView with the responsibility to report player’s moves. ñA PlayerView observes a Player, and updates the text field when the Player takes a turn.

34 33May 2004NH-Chapter 18 Delaying IdependentPlayer’s move  NimController invokes Game’s play, ñonce for InteractivePlayer, ñonce for IndependentPlayer. ñNeed a delay between the two play invocations.

35 34May 2004NH-Chapter 18 Delaying IdependentPlayer’s move ñAttempt to delay the two plays fails. ñApplication will pause, but moves appear to take place at the same time. public void actionPerformed (ActionEvent e) { … user.setNumberToTake(number); game.play(); nhUtilities.utilities.Control.sleep(2); //delay game.play(); … }

36 35May 2004NH-Chapter 18 Delaying IdependentPlayer’s move user presses button thread sleeps for two seconds display updates resulting form display is updated display updates resulting from InteractivePlayer move are scheduled IndependentPlayer move are scheduled button-press event handler starts button-press event handler completes Event dispatch thread

37 36May 2004NH-Chapter 18 Scheduling a move to delay the action  NimController uses javax.swing.Timer to schedule IndependentPlayer’s play seconds after play of InteractivePlayer. ñUser’s Button-press event handling is complete. ñIndependentPlayer’s move occurs after and when scheduled.

38 37May 2004NH-Chapter 18 MVC and Swing components ñSwing components are structured using MVC pattern. ñEach Swing JComponent has an associated model object responsible for maintaining component’s state. ñJButton or JCheckBox has a ButtonModel, ñ JTextArea or JTextField has a Document. ñA Swing component delegates view and control responsibilities to its UI delegate.  The package javax.swing.plaf contains an abstract delegate class for each Swing component.

39 38May 2004NH-Chapter 18 Summary ñOverview basic format of Model-View-Controller pattern. ñMVC commonly used to structure event-driven graphical user interfaces. ñWith MVC, interface responsibilities are partitioned into two segments: ñview has display responsibilities, ñcontroller modifies model in accordance with user input.

40 39May 2004NH-Chapter 18 Summary ñDeveloped three views of a right triangle. ñNoted Java Observer interface and Observable class for implementing the observes relationship. ñFundamental relationship between view and model is observes, implemented by ñmaking model object an extension of the class Observable, ñview implements interface Observer. ñAdded a graphical user interface to the nim game, using the MVC pattern.

41 40May 2004NH-Chapter 18 Summary ñSwing components are structured along the lines of MVC. ñEach Swing component has ñan associated model object responsible for maintaining component’s state. ña UI delegate, to which view and control responsibilities are delegated. ñThis structure allows to change application look-and- feel in a system-independent way.


Download ppt "An Introduction to Programming and Object Oriented Design using Java 2 nd Edition. May 2004 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface."

Similar presentations


Ads by Google