Presentation is loading. Please wait.

Presentation is loading. Please wait.

Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010.

Similar presentations


Presentation on theme: "Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010."— Presentation transcript:

1 Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010

2 MVC (Model View Controller) 2 / 31 “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

3 MVC (Model View Controller) 3 / 31 “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). 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. A view requests information from the model that it uses to generate an output representation to the user.” -Wikipedia

4 Outline 1 Using the Default Models 2 File Browser 4 / 31

5 Outline 1 Using the Default Models 2 File Browser 5 / 31

6 Using the Default Models Swing supplies default, mutable models for all widgets: List Tree (nodes) Table Spinner and Slider... 6 / 31

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

8 Constructor with Default List Model 8 / 31 public SimpleList() { super("List Demo"); 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);... }

9 Adding and Removing with the Default Model 9 / 31 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]); }

10 Outline 1 Using the Default Models 2 File Browser 10 / 31

11 A Simple File Broswer 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 11 / 31

12 Outline 1 Using the Default Models 2 File Browser Tree Model Tree Cell Renderer List Cell Renderer The File Broswer Writing a Swing Worker 12 / 31

13 A Model for the Tree View Tree model Get root Get children count per node Get child for index Check if a node is a leaf Directories tree model Root Top directory Children Files in directory Leaf An directory without sub-directories 13 / 31

14 The Directories Tree Model 14 / 31 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); }

15 Tree Model Inferface Methods 15 / 31 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; }

16 Tree Model Interface Methods (cont’d) 16 / 31 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); }

17 Empty Tree Model Interface Methods 17 / 31 public void valueForPathChanged(TreePath p, Object v) public void addTreeModelListener(TreeModelListener l) public void removeTreeModelListener(TreeModelListener l) Tree nodes are not added or removed dynamically in this model, so the tree model listener is redundant

18 Outline 1 Using the Default Models 2 File Browser Tree Model Tree Cell Renderer List Cell Renderer The File Broswer Writing a Swing Worker 18 / 31

19 Rendering a Directories Tree Cell public class DirTreeCellRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus ) { super.getTreeCellRendererComponent(...); File tRoot = (File) tree.getModel().getRoot(); File tFile = (File) value; setText(tRoot.equals(value) ? tFile.getAbsolutePath() : tFile.getName()); setIcon(expanded ? openIcon : closedIcon); return this; }} 17 / 31

20 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

21 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

22 Files List Model Interface Methods 22 / 31 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); }

23 Outline 1 Using the Default Models 2 File Browser Tree Model Tree Cell Renderer List Cell Renderer The File Broswer Writing a Swing Worker 23 / 31

24 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; } } 22 / 31

25 Outline 1 Using the Default Models 2 File Browser Tree Model Tree Cell Renderer List Cell Renderer The File Broswer Writing a Swing Worker 25 / 31

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

27 File Broswer Constructor 27 / 31 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));... }

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

29 Listening to List Events 29 / 31 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(); }

30 Outline 1 Using the Default Models 2 File Browser Tree Model Tree Cell Renderer List Cell Renderer The File Broswer Writing a Swing Worker 30 / 31

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

32 Do in Background 32 / 31 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; }

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


Download ppt "Swing, part 2 Tutorial 07 1 / 31 Leonid Barenboim 25/4/2010."

Similar presentations


Ads by Google