עקרונות תכנות מונחה עצמים תרגול 8: MVC. Outline  MVC  Using the default models  Example- File Browser.

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.
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
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.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
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.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Object-Oriented Analysis and Design
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Object Oriented Design & Patterns Part 1. 2 Design Patterns Derived from architectural patterns: –rules for design of buildings –describe common problems,
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
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.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
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.
CS12420 – Swing and threads Lynda Thomas
DAT602 Database Application Development Lecture 6 JAVA Swing.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
CIS 644 Aug. 25, 1999 tour of Java. First … about the media lectures… we are experimenting with the media format please give feedback.
Files. What are files? A series of data bits. a place for output a place to obtain input.
Chapter 19 Designing the GUI front-end: the Model-View-Controller pattern.
LAB 1CSIS04021 Briefing on Assignment One & RMI Programming February 13, 2007.
Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010.
CSE 219 Patterns in Programming More Design Patterns.
עקרונות תכנות מונחה עצמים תרגול 6 - GUI. סיכום ביניים GUI:  Swing  Basic components  Event handling  Containers  Layouts.
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.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Trees CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
More GUIs, events, static. model.addElement(335); model.addElement(436); } private JTextArea lineDisplay = new JTextArea("Could have\nseveral lines\nhere");
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
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.
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.
1 Chapter 24 Advanced Swing Components. 2 Objectives · To understand the Swing model-view-controller architecture (§24.2). · To use JSpinner to scroll.
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.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Overview Project 2 JFileChooser StringTokenizers Vectors/arrays.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
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.
עקרונות תכנות מונחה עצמים תרגול 7: כתיבה לקבצים
Advanced Swing Trees.
Lecture 27 Creating Custom GUIs
Advanced Swing Lists.
CompSci 280 S Introduction to Software Development
Creating and Modifying Text part 2
null, true, and false are also reserved.
עקרונות תכנות מונחה עצמים תרגול 8: MVC
Advanced GUIs and Graphics
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

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

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

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

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

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

 The file browser shows:  Directories tree  List of files in the selected directory  Content of the selected file  Plus:  The event dispatcher thread should not hang while reading the content of a file  Only the event dispatcher thread should update the screen A Simple File Broswer

Example 2 FileBrowser

 Tree Model  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker Model View Controller

File Browser  Tree Model  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker

 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 A Model for the Tree View

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); } Inner 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 tFiles = Arrays.asList(list((File)parent)); return tFiles.indexOf((File)child); }

File Browser  Tree Model  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker

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; }} Rendering a Directories Tree Cell

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

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

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

File Browser  Tree Model  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker

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  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker

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

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) { // Gotcha 1: Check if value is adjusting if (e.getValueIsAdjusting()) return; // Gotcha 2: Don’t use e’s indices File tFile = (File) getFiles().getSelectedValue(); getContent().setText(""); // Gotcha 3: Don’t re-use a worker SwingWorker tWorker = new FileReaderWorker(tFile, getContent()); tWorker.execute(); }

File Browser  Tree Model  Tree Cell Render  List Cell Render  The File Browser  Writing a swing worker

Swing worker  Abstract Class: SwingWorker  protected abstract T doInBackground()  protected void process(List chunks)  protected void done()  protected final void publish(V... chunks)

Writing a Swing Worker public class FileReaderWorker extends SwingWorker { private File _file; private JTextArea _text;... }

Do in Background protected Void doInBackground() throws Exception { try { BufferedReader tIn = new BufferedReader(new FileReader(getFile())); String tLine; while ((tLine = tIn.readLine()) != null) { publish(tLine); } tIn.close(); } catch (IOException e) { publish(e.getMessage()); } return null; }

Process and Done protected void process(List chunks) { for (String tLine : chunks) { getText().append(tLine + "\n"); } protected void done() { getText().setCaretPosition(0); }