עקרונות תכנות מונחה עצמים תרגול 8: MVC. Outline MVC Using the default...
-
Upload
gloria-simpson -
Category
Documents
-
view
249 -
download
8
description
Transcript of עקרונות תכנות מונחה עצמים תרגול 8: MVC. Outline MVC Using the default...
מונחה תכנות עקרונותעצמים
MVC: 8תרגול
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 { pr ivate JLis t _ l i s t ;
pr ivate 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 JBut ton(" -" ) ; // calls rem()tBar.add(tRem);getContentPane().add(tBar, BorderLayout.NORTH);. . .}
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 ] );} }
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
File Browser
Tree Model Tree Cell Render List Cell Render The File Browser Writing a swing worker
ModelView
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
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
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 ;
}
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 ) ;}
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
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
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
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 ) ;
}
File Browser
Tree Model Tree Cell Render List Cell Render The File Browser Writing a swing worker
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 ;
}{
File Browser
Tree Model Tree Cell Render List Cell Render The File Browser Writing a swing worker
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 ;
. . .}
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 ) ) ;. . .}
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) ;
}
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();}
File Browser
Tree Model Tree Cell Render List Cell Render The File Browser Writing a swing worker
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)
Writing a Swing Worker
public class FileReaderWorker extends SwingWorker<Void, String>{private F i le _ f i l e ;pr ivate JTextArea _text ;
. . .}
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 ;}
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);
}