עקרונות תכנות מונחה עצמים תרגול 8: mvc. outline mvc using the default...

39
תתתתתתת תתתתת תתתתת תתתתת תתתתת8 : MVC

Upload: gloria-simpson

Post on 06-Jan-2018

247 views

Category:

Documents


8 download

DESCRIPTION

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

TRANSCRIPT

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

מונחה תכנות עקרונותעצמים

MVC: 8תרגול

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

Outline

MVC Using the default models Example- File Browser

Page 3: עקרונות תכנות מונחה עצמים תרגול 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

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

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

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

MVC - View

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

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

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)

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

Outline

MVC Using the default models Example- File Browser

Page 8: עקרונות תכנות מונחה עצמים תרגול 8: MVC. 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

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

getModel

public boolean isPressed() { return

getModel().isPressed(); }

JButton+isPressed: boolean+getModel: ButtonModel

ButtonModel

+isPressed: boolean

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

Example 1

DefaultListModel

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

Default List Model Example

Add and remove elements from a list using the default model:

public class SimpleList extends JFrame { pr ivate JLis t _ l i s t ;

pr ivate DefaultListModel _model;

. . .

}

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

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 JBut ton(" -" ) ; // calls rem()tBar.add(tRem);getContentPane().add(tBar, BorderLayout.NORTH);. . .}

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

Adding and Removing with the Default Model

private void add() {Str ing tVal = JOptionPane.showInputDialog(

t h i s , "Add new value") ;i f ( tVal != nu l l )

{ getModel().add(getModel().getSize(), tVa l ) ;

}}

private void rem() {i n t [ ] i s = getList() .getSelectedIndices();

Ar rays .sor t ( is ) ;f o r ( i n t i = is. length - 1; i >= 0; i - - )

{ getModel().remove(is[ i ] );} }

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

Outline

MVC Using the default models Example- File Browser

Page 15: עקרונות תכנות מונחה עצמים תרגול 8: MVC. 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

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

Example 2

FileBrowser

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

File Browser

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

ModelView

Controller

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

File Browser

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

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

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

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

The Directories Tree Model

publ ic class DirTreeModel implements TreeModel { pr iva te F i l e _ d i r ;

publ ic DirTreeModel(File d i r ) { s e t D i r ( d i r ) ;

}

pr ivate s t a t i c F i l e F i l t e r _FILTER = new F i l e F i l t e r ( ) { publ ic boolean accept(Fi le f i l e ) {return f i l e . i s D i r e c t o r y ( ) ;

}} ;

pr ivate F i l e [ ] l i s t ( F i l e f i l e ) { return f i l e . l i s tF i l es (_F ILTER) ;

}

Inner class

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

Tree Model Inferface Methods

publ ic Object getRoot() { re turn g e tD i r ( ) ;

}

publ ic Object getChild(Object parent, i n t index) {F i l e [ ] tChildren = l i s t ( ( F i l e ) p a r e n t ) ;

re turn tChi ldren[ index ] ;}

publ ic i n t getChildCount(Object parent) { return l i s t ( ( F i l e ) p a r e n t ) . l e n g t h ;

}

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

Tree Model Interface Methods (cont’d)

publ ic boolean isLeaf(Object node) { return getChildCount(node) == 0 ;

}

publ ic i n t getIndexOfChild(Object parent, Object c h i l d ) { L is t<Fi le> t F i l e s = A r ra ys .as L i s t ( l i s t ( (F i l e )pa re n t ) ) ;

return tF i l es . i nd exOf ( (F i l e ) ch i l d ) ;}

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

File Browser

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

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

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

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

Files List Model

publ ic class FilesListModel implements ListModel { pr iva te F i l e _ d i r ;pr ivate L is t<Fi le> _ f i l e s ;pr ivate Collect ion<ListDataListener> _ l i s teners ;

pr ivate s t a t i c F i l e F i l t e r _FILTER = new F i l e F i l t e r ( ) { publ ic boolean accept(Fi le f ) {

return f . i s F i l e ( ) ;}

} ;

publ ic Fi lesListModel() {setListeners(new LinkedList<ListDataListener>());

setFiles(Collections.EMPTY_LIST);}

18 / 31

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

Setting the Directory

publ ic F i l e g e t D i r ( ) { re turn _ d i r ;

}

publ i c void s e t D i r ( F i l e d i r ) {_d i r = d i r ;i n t tOldSize = ge tS ize( ) ;F i l e [ ] t F i l e s = d i r. l i s tF i l es ( _F I LT ER ) ; s e t F i l es (A r r a y s . a s L i s t ( t F i l es ) ) ;i n t tMax = Math.max(tOldSize, ge t S i ze ( ) ) ; ListDataEvent tEv t = new Lis tDataEvent( th is ,LDE.CONTENTS_CHANGED, 0, tMax);f o r (L is tDataLis tener tL i s tener : ge tL i s teners ( ) ) {

tListener.contentsChanged(tEvt) ;{{

19 / 31

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

Files List Model Interface Methods

publ ic i n t getSize() { return g e t F i l e s ( ) . s i z e ( ) ;

}

publ ic Object getElementAt( int index) { return ge tF i les ( ) .ge t ( index) ;

}

publ ic void addListDataListener(ListDataListener l ) { ge tL i s teners ( ) .add ( l ) ;

}

publ ic void removeListDataListener(ListDataListener l ) { getLis teners() . remove(l ) ;

}

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

File Browser

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

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

Rendering a Files List Cell

publ ic class Fi lesListCellRenderer extends DefaultListCellRenderer{ pr ivate s t a t i c Color _ALT = new Color(220, 220, 220); publ ic Component getListCellRendererComponent(

JL is t l i s t , Object value, i n t index, boolean isSelected, boolean cellHasFocus(

{ super.getListCellRendererComponent(...); F i l e f = ( F i l e ) value; setText(f.getName());

i f ( ! isSelected && index % 2 == 0){ setBackground(_ALT);

{ return t h i s ;

}{

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

File Browser

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

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

Putting It Together

publ ic class FileBrowser extends JFrameimplements TreeSelectionListener,

L istSelect ionListener{pr ivate JTree _ t ree ; pr ivate JTextArea _content;pr ivate JL i s t _ f i l e s ;

. . .}

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

File Broswer Constructor

publ ic Fi leBrowser(File f i l e ) { super(f i le .getAbsolutePath() ) ;

// TreesetTree(new JTree(new Di rTreeModel ( f i le )) ) ;

getTree().setCellRenderer(new DirTreeCellRenderer()); getTree().addTreeSelectionListener(this);

// File listsetFiles(new JList(new F i lesL is tMode l ( ) ) ) ;

getFiles().setCellRenderer(new Fi lesL is tCel lRenderer( ) ) ; getFiles().setSelectionMode(LSM.SINGLE_SELECTION); ge tF i les( ) .addL is tSe lec t ionLis tener( th is ) ;

// Text areasetContent(new JTextArea(10, 30 ) ) ;. . .}

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

Listening to Tree Events

public void valueChanged(TreeSelectionEvent e) {F i le tD i r = ( F i l e ) e.getPath().getLastPathComponent(); ( (Fi lesListModel)getFiles() .getModel()) .setDir( tDir) ;

}

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

Listening to List Events

public void valueChanged(ListSelectionEvent e) {// Gotcha 1: Check if value is adjustingi f (e.getValueIsAdjusting())

return;// Gotcha 2: Don’t use e’s indices

Fi le t Fi l e = ( Fi l e ) getFiles().getSelectedValue(); getContent().setText("");

// Gotcha 3: Don’t re-use a workerSwingWorker tWorker = new FileReaderWorker(tFile,

getContent()); tWorker.execute();}

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

File Browser

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

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

Swing worker

Abstract Class: SwingWorker <T,V> protected abstract T doInBackground() protected void process(List<V> chunks) protected void done() protected final void publish(V... chunks)

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

Writing a Swing Worker

public class FileReaderWorker extends SwingWorker<Void, String>{private F i le _ f i l e ;pr ivate JTextArea _text ;

. . .}

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

Do in Background

protected Void doInBackground() throws Exception { t r y {

BufferedReader t I n = new BufferedReader(new Fi leReader (getFi le() ) ) ;

Str ing t L i ne ; while ( ( t L ine = t In . readL ine( ) ) != n u l l ) {

pub l i sh ( tL ine) ; }

t I n . c l o s e ( ) ; } catch (IOException e) {

publish(e.getMessage());

} return n u l l ;}

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

Process and Done

protected void process(List<String> chunks) { f o r (St r ing tLine : chunks) {getText().append(tLine + " \ n " ) ;

}}

protected void done() { getText() .setCaretPosit ion(0);

}