עקרונות תכנות מונחה עצמים תרגול 8: MVC

Slides:



Advertisements
Similar presentations
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Advertisements

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.
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.
Michael Brockway Advanced Applications Development in Java Model-View-Controller Architecture l MVC Architecture l Delegate-Model Architecture l Observer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 36 JTable and JTree.
THE SWING UI TOOLKIT Mostly from “The Swing Connection”The Swing Connection.
© Marty Hall, Larry Brown Web core programming 1 Advanced Swing Custom Data Models and Cell Renderers.
Object-Oriented Analysis and Design
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
Composite Design Pattern. Motivation – Dynamic Structure.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
MVC CompSci 230 S Software Construction. MVC Architecture  A typical application includes software to  maintain application data,  document text.
MVC and Swing IAT 351 Week 7 Lecture/tutorial Lyn Bartram.
DAT602 Database Application Development Lecture 6 JAVA Swing.
Files. What are files? A series of data bits. a place for output a place to obtain input.
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.
Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010.
CSE 219 Patterns in Programming More Design Patterns.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 24 Advanced Swing.
Copyright © 2002 Systek The Adapter Pattern Overview And Experience Report Johannes Brodwall, Systek AS.
3461 Model-View Controller Advanced GUI concepts.
Trees CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java Programming: Advanced Topics 1 Components and Facilities for Rich Graphical User Interfaces Chapter 7.
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.
More GUIs, events, static. model.addElement(335); model.addElement(436); } private JTextArea lineDisplay = new JTextArea("Could have\nseveral lines\nhere");
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 35 MVC and Swing MVC.
JTree javax.swing.tree javax.swing.event. Components JTree and JTable COMPONENT – Model – Selection Model – Editor – Renderer.
CS GUI Frameworks CS 3331 Fall CS 3331 Outline MVC Model GUI components (widgets) Layout managers Handling events.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many of others 1.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 31 JTable and JTree.
Swinging in Your Java Playground. Background Swing is a part of the Java Foundation Classes (JFC). The JFC is made up of features intended to give a programmer.
Swing - 2 Session 13. Swing - 2 / 2 of 38 Objectives (1) Discuss trees and tables Discuss progress bars Discuss MVC architecture Describe menus.
Computer Science 209 GUIs Model/View/Controller Layouts.
1 Chapter 24 Advanced Swing Components. 2 Objectives · To understand the Swing model-view-controller architecture (§24.2). · To use JSpinner to scroll.
עקרונות תכנות מונחה עצמים תרגול 8: MVC. Outline  MVC  Using the default models  Example- File Browser.
Advanced Swing Custom Data Models and Cell Renderers.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Creating a GUI Class An example of class design using inheritance and interfaces.
Lecture 33: More Graphical User Interface (GUI) Announcements & Review Read Ch GU1 & GU2 Cohoon & Davidson Ch 14 Reges & Stepp Lab 10 set game due 4/26.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 3: Layout Basics.
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 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Advanced Swing Trees. Contents I.Introduction to Trees II. Simple Trees III. Editing Trees and Tree Paths IV. Node Enumeration V. Rendering Nodes VI.
CompSci 230 S Software Construction
GUIs and Events Rick Mercer.
CSC 222: Object-Oriented Programming
Topic 2: binary Trees COMP2003J: Data Structures and Algorithms 2
“Form Ever Follows Function” Louis Henri Sullivan
Java GUI.
GUIs Model/View/Controller Layouts
Java Swing.
Nodes & Explorer Views Geertjan Wielenga Sun Microsystems.
Advanced Swing Trees.
Lecture 27 Creating Custom GUIs
Advanced Swing Lists.
Composite Design Pattern
CompSci 280 S Introduction to Software Development
A Quick Java Swing Tutorial
Creating and Modifying Text part 2
Chapter 13: Advanced GUIs and Graphics
Graphical user interface-based programming
A Quick Java Swing Tutorial
A Heap Implementation Chapter 26 Adapted from Pearson Education, Inc.
Advanced GUIs and Graphics
Heaps.
Presentation transcript:

עקרונות תכנות מונחה עצמים תרגול 8: MVC

Outline MVC Using the default models Example- File Browser

MVC (Model View Controller) “Model–view–controller (MVC) is a software architectural pattern  for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.” -Wikipedia

MVC - Model A model stores data that is altered by the controller and displayed in the view. Whenever there is a change to the data it is updated by the controller

MVC - View A view requests information from the model that it uses to generate an output representation to the user

MVC - Controller A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document)

Outline MVC Using the default models Example- File Browser

Using the Default Models Swing supplies default, mutable models for all widgets: List Tree (nodes) Table Spinner Slider …

getModel public boolean isPressed() { return getModel().isPressed(); } JButton +isPressed: boolean +getModel: ButtonModel ButtonModel +isPressed: boolean public boolean isPressed() { return getModel().isPressed(); }

Example 1 DefaultListModel

Default List Model Example Add and remove elements from a list using the default model: public class SimpleList extends JFrame { private JList _list; private DefaultListModel _model; ... }

Constructor with Default List Model public SimpleList() { super( "ListDemo" ); setModel(new DefaultListModel()); setList(new JList(_model)); getList().setPreferredSize(new Dimension(100, 300)); getContentPane().add(getList(), BorderLayout.CENTER); JToolBar tBar = new JToolBar(); JButton tAdd = new JButton("+"); // calls add() tBar.add(tAdd); JButton tRem = new JButton("-"); // calls rem() tBar.add(tRem); getContentPane().add(tBar, BorderLayout.NORTH); ... }

Adding and Removing with the Default Model private void add() { String tVal = JOptionPane.showInputDialog( this, "Add new value"); if (tVal != null) { getModel().add(getModel().getSize(), tVal); } private void rem() { int[] is = getList().getSelectedIndices(); Arrays.sort(is); for (int i = is.length - 1; i >= 0; i--) { getModel().remove(is[i]); }}

Outline MVC Using the default models Example- File Browser

A Simple File Broswer The file browser shows: Directories tree List of files in the selected directory Content of the selected file

Example 2 FileBrowser

Model View Controller File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser View Controller

File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser

A Model for the Tree View Tree model Get Root Get Children count per node Get Childe for index Check if a node is leaf Directories tree model Root = Top directory Children = sub-directories in the directory Leaf = A directory without sub-directory

The Directories Tree Model public class DirTreeModel implements TreeModel { private File _dir; public DirTreeModel(File dir) { setDir(dir); } private static FileFilter _FILTER = new FileFilter() { public boolean accept(File file) { return file.isDirectory(); }; private File[] list(File file) { return file.listFiles(_FILTER); Anonymous class

Tree Model Inferface Methods public Object getRoot() { return getDir(); } public Object getChild(Object parent, int index) { File[] tChildren = list((File)parent); return tChildren[index]; public int getChildCount(Object parent) { return list((File)parent).length;

Tree Model Interface Methods (cont’d) public boolean isLeaf(Object node) { return getChildCount(node) == 0; } public int getIndexOfChild(Object parent, Object child) { List<File> tFiles = Arrays.asList(list((File)parent)); return tFiles.indexOf((File)child);

File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser

TreeCellRenderer Defines the requirements for an object that displays a tree node. Implemented by DefaultTreeCellRenderer getTreeCellRendererComponent(..) gets the components properties and configures the renderer Add it to your VIEW

Rendering a Directories Tree Cell public class DirTreeCellRender extends DefaultTreeCellRender{ public Component GetTreeCellRenderComponent( JTree tree, Object Value, boolean cell, boolean expended, boolean leaf, int row, boolean hasFocus) { super.getCellRenderComponent(…); File tRoot = (File) getModel().getRoot(); File tFile = (File)value; setText(tRoot.equals(value)?tFile.getAbsolutePath(): tFile.getName()); setIcon( expanded? openIcon : closeIcon ); return this; }}

File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser

List Model Our List Model is mutable (changes when we change directory) This means we need to implement the following interface methods: addListDataListener(ListDataListener l) removeListDataListener(ListDataListener l) Otherwise, the list view won’t update when the model is changed

Files List Model public class FilesListModel implements ListModel { private File _dir; private List<File> _files; private Collection<ListDataListener> _listeners; private static FileFilter _FILTER = new FileFilter() { public boolean accept(File f) { return f.isFile(); } }; public FilesListModel() { setListeners(new LinkedList<ListDataListener>()); setFiles(Collections.EMPTY_LIST); 18 / 31

Files List Model Interface Methods public int getSize() { return getFiles().size(); } public Object getElementAt( int index) { return getFiles().get(index); public void addListDataListener(ListDataListener l) { getListeners().add(l); public void removeListDataListener(ListDataListener l) { getListeners().remove(l);

Setting the Directory public File getDir() { return _dir; } public void setDir(File dir) { _dir = dir; int tOldSize = getSize(); File[] tFiles = dir.listFiles(_FILTER); setFiles(Arrays.asList(tFiles)); int tMax = Math.max(tOldSize, getSize()); ListDataEvent tEvt = new ListDataEvent(this,LDE.CONTENTS_CHANGED, 0,tMax); for (ListDataListener tListener : getListeners()) { tListener.contentsChanged(tEvt); { 19 / 31

File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser

Rendering a Files List Cell public class FilesListCellRenderer extends DefaultListCellRenderer{ private static Color _ALT = new Color(220, 220, 220); public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus( { super.getListCellRendererComponent(...); File f = (File) value; setText(f.getName()); if (!isSelected && index % 2 == 0){ setBackground(_ALT); return this; }

File Browser Tree Model List Model Tree Cell Render List Cell Render The File Browser

Putting It Together public class FileBrowser extends JFrame implements TreeSelectionListener, ListSelectionListener { private JTree _tree; private JTextArea _content; private JList _files; ... }

File Broswer Constructor public FileBrowser(File file) { super(file.getAbsolutePath()); // Tree setTree(new JTree(new DirTreeModel(file))); getTree().setCellRenderer(new DirTreeCellRenderer()); getTree().addTreeSelectionListener(this); // File list setFiles(new JList(new FilesListModel())); getFiles().setCellRenderer(new FilesListCellRenderer()); getFiles().setSelectionMode(LSM.SINGLE_SELECTION); getFiles().addListSelectionListener(this); // Text area setContent(new JTextArea(10, 30)); ... } View View Model Model View with default model

Listening to Tree Events public void valueChanged(TreeSelectionEvent e) { File tDir = (File) e.getPath().getLastPathComponent(); ((FilesListModel)getFiles().getModel()).setDir(tDir); }

Listening to List Events public void valueChanged(ListSelectionEvent e) { // If the value is still adjusting we get two events, Un-select and select if (e.getValueIsAdjusting()) return; File tFile = (File) getFiles().getSelectedValue(); getContent().setText(""); try { BufferedReader tIn = new BufferedReader(new FileReader(tFile)); String tLine; while ((tLine = tIn.readLine()) != null) { getContent().append(tLine + "\n"); } tIn.close(); getContent().setCaretPosition(0); } … }