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

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.
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.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
JSP Architecture Outline  Model 1 Architecture  Model 2 Architecture.
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.
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.
LAB 1CSIS04021 Briefing on Assignment One & RMI Programming February 13, 2007.
CSE 219 Patterns in Programming More Design Patterns.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
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.
Swing MVC Application Layering A Layer is a collection of components that Perform similar tasks. Perform similar tasks. Isolate implementation details.
Trees CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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");
SWING 101. IF YOU GET LOST - IMPORTANT LINKS  Swing articles:
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.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
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) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
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.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
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.
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.
Advanced Swing Trees.
Lecture 27 Creating Custom GUIs
Advanced Swing Lists.
A Quick Java Swing Tutorial
Creating and Modifying Text part 2
עקרונות תכנות מונחה עצמים תרגול 8: MVC
A Quick Java Swing Tutorial
Advanced GUIs and Graphics
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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