Search Results

Search found 23 results on 1 pages for 'treemodel'.

Page 1/1 | 1 

  • Dojo treemodel- adding large number of items

    - by Ashley
    I am trying to add a large number of items (100+) to my tree via ForestStoreModel by calling newItem in a loop. This seems to be quite slow and locks up the browser. Is there any way I can do something similar to grid's beginUpdate & endUpdate? I want to basically 'turn off' my tree, add 100 items in a batch, then 'turn on' my tree. Any ideas? Thanks!

    Read the article

  • Creating a complex tree model in Qt

    - by Zeke
    I'm writing an IRC Client (yes another one). Long story short. I'm writing a Server dialogue that keeps a list of this: Identity Networks Channels Addresses I have 3 different list views that will be for the Networks, Channels and Addresses. When the user changes the Identity (combo box). The network listview will lookup all the networks for that specific Identity. After it loads up the Networks it will automatically select the first network and then load all the channels and addresses for that specific network. The problem is I want to have 3 views for 1 model, to minimise all the memory and the loading of data. So that it makes it much easier to manage and not do a bunch of work. If you'd look at QColumnView it's the same exact thing. But I don't need it to be on one exact page since the views are on entirely different tabs to make it easier to go through the Server dialogue. I'm wondering what will be the best way to go about handling this complexity. The information is stored in a SQLite database. I already have the classes written to extract and store it. Just the modelling is the painful part of this solution.

    Read the article

  • How-to read data from selected tree node

    - by Frank Nimphius
    Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} By default, the SelectionListener property of an ADF bound tree points to the makeCurrent method of the FacesCtrlHierBinding class in ADF to synchronize the current row in the ADF binding layer with the selected tree node. To customize the selection behavior, or just to read the selected node value in Java, you override the default configuration with an EL string pointing to a managed bean method property. In the following I show how you change the selection listener while preserving the default ADF selection behavior. To change the SelectionListener, select the tree component in the Structure Window and open the Oracle JDeveloper Property Inspector. From the context menu, select the Edit option to create a new listener method in a new or an existing managed bean. Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} Normal 0 false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} For this example, I created a new managed bean. On tree node select, the managed bean code prints the selected tree node value(s) import java.util.List; import javax.el.ELContext; import javax.el.ExpressionFactory; import javax.el.MethodExpression; import javax.faces.application.Application; import javax.faces.context.FacesContext; import java.util.Iterator; import oracle.adf.view.rich.component.rich.data.RichTree; import oracle.jbo.Row; import oracle.jbo.uicli.binding.JUCtrlHierBinding; import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding; import org.apache.myfaces.trinidad.event.SelectionEvent; import org.apache.myfaces.trinidad.model.CollectionModel; import org.apache.myfaces.trinidad.model.RowKeySet; import org.apache.myfaces.trinidad.model.TreeModel; public class TreeSampleBean { public TreeSampleBean() {} public void onTreeSelect(SelectionEvent selectionEvent) { //original selection listener set by ADF //#{bindings.allDepartments.treeModel.makeCurrent} String adfSelectionListener = "#{bindings.allDepartments.treeModel.makeCurrent}";   //make sure the default selection listener functionality is //preserved. you don't need to do this for multi select trees //as the ADF binding only supports single current row selection     /* START PRESERVER DEFAULT ADF SELECT BEHAVIOR */ FacesContext fctx = FacesContext.getCurrentInstance(); Application application = fctx.getApplication(); ELContext elCtx = fctx.getELContext(); ExpressionFactory exprFactory = application.getExpressionFactory();   MethodExpression me = null;   me = exprFactory.createMethodExpression(elCtx, adfSelectionListener,                                           Object.class, newClass[]{SelectionEvent.class});   me.invoke(elCtx, new Object[] { selectionEvent });     /* END PRESERVER DEFAULT ADF SELECT BEHAVIOR */   RichTree tree = (RichTree)selectionEvent.getSource(); TreeModel model = (TreeModel)tree.getValue();  //get selected nodes RowKeySet rowKeySet = selectionEvent.getAddedSet();   Iterator rksIterator = rowKeySet.iterator();   //for single select configurations,this only is called once   while (rksIterator.hasNext()) {     List key = (List)rksIterator.next();     JUCtrlHierBinding treeBinding = null;     CollectionModel collectionModel = (CollectionModel)tree.getValue();     treeBinding = (JUCtrlHierBinding)collectionModel.getWrappedData();     JUCtrlHierNodeBinding nodeBinding = null;     nodeBinding = treeBinding.findNodeByKeyPath(key);     Row rw = nodeBinding.getRow();     //print first row attribute. Note that in a tree you have to     //determine the node type if you want to select node attributes     //by name and not index      String rowType = rw.getStructureDef().getDefName();       if(rowType.equalsIgnoreCase("DepartmentsView")){      System.out.println("This row is a department: " +                          rw.getAttribute("DepartmentId"));     }     else if(rowType.equalsIgnoreCase("EmployeesView")){      System.out.println("This row is an employee: " +                          rw.getAttribute("EmployeeId"));     }        else{       System.out.println("Huh????");     }     // ... do more useful stuff here   } } -------------------- Download JDeveloper 11.1.2.1 Sample Workspace

    Read the article

  • How to add a separator in a PyGTK combobox?

    - by mkotechno
    I'm using gtk.combo_box_new_text() to make combobox list, this uses a gtk.ListStore to store only strings, so there are some way to add a separator between items without use a complex gtk.TreeModel? If this is not possible, what is the simplest way to use a gtk.TreeModel to able secuential widget addition?

    Read the article

  • Qt, no such slot error

    - by Martin Beckett
    I'm having a strange problem with slots in Qt4.6 I have a tree control that I am trying to fire an event back to the mainwindow to edit something. I have boiled it down to this minimal example: class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(int argc, char **argv ); private Q_SLOTS: void about() {QMessageBox::about(this, "about","about"); } // Just the defaul about box void doEditFace() {QMessageBox::about(this, "test","doEditFace"); } // pretty identical .... } class TreeModel : public QAbstractItemModel { Q_OBJECT Q_SIGNALS: void editFace(); ... } In my Mainwindow() I have connect(treeModel, SIGNAL(editFace()), this, SLOT(about())); // returns true connect(treeModel, SIGNAL(editFace()), this, SLOT(doEditFace())); // returns false When I run it the second line gives a warning. Object::connect: No such slot MainWindow::doEditFace() in \src\mainwindow.cpp:588 As far as I can see the doEditFace() is in the moc_ qmeta class perfectly correctly. And the edit event fires and pops up the about box. The order doesn't matterm if I connect the about box second it still works but my slot doesnt! vS2008 windowsXP qt4.6.2

    Read the article

  • Catch PyGTK TreeView reorder

    - by mkotechno
    I have a simple gtk.TreeView with a gtk.ListStore model and set_reorderable(True), I want to catch the signal/event emited when the user reorder through drag&drop the list, but the documentation does not help much: "The application can listen to these changes by connecting to the model's signals" So I tried to connect the model (ListStore) signals... but surprise! ListStore has no signals, so you are dispatched to TreeModel signals, then I tried to connect with the TreeModel "rows-reordered" signal with no lucky. How should I catch the list reorder performed by the user?

    Read the article

  • Display a tree dijit using zend framework

    - by churris43
    I am trying to display a tree of categories and subcategories by using dijits with zend framework. Haven't been able to find a good example. This is what I've got: Basically I got the following code as my action: class SubcategoriesController extends Zend_Controller_Action{ ..... public function loadtreeAction() { Zend_Dojo::enableView($this->view); Zend_Layout::getMvcInstance()->disableLayout(); //Creating a sample tree of categories and subcategories $a["cat1"]["id"] = "id1"; $a["cat1"]["name"] = "Category1"; $a["cat1"]["type"] = "category"; $subcat1 = array("id" => "Subcat1","name" => "Subcategory1" , "type" => "subcategory"); $subcat2 = array("id" => "Subcat12","name" => "Subcategory12" , "type" => "subcategory"); $a["cat1"]["children"] = array($subcat1,$subcat2); $treeObj = new Zend_Dojo_Data('id', $a); $treeObj->setLabel('name'); $this->view->tree = $treeObj->toJson(); } .... } And on my view: <?php $this->dojo()->requireModule('dojo.data.ItemFileReadStore'); $this->dojo()->requireModule('dijit.Tree'); $this->dojo()->requireModule('dojo.parser'); ?> <div dojoType="dojo.data.ItemFileReadStore" url="/Subcategories/loadtree" jsId="store"></div> <div dojoType="dijit.tree.ForestStoreModel" jsId="treeModel" store="store" rootId="root" rootLabel="List of Categories" childrenAttrs="children" query="{type:'category'}"></div> <div dojoType="dijit.Tree" model="treeModel" labelAttrs="ListOfCategories"></div> It doesn't even seem to try to load the tree at all. Any help is appreciated

    Read the article

  • Implement Tree/Details With Taskflow Regions Using EJB

    - by Deepak Siddappa
    This article describes on Display Tree/Details using taskflow regions.Use Case DescriptionLet us take scenario where we need to display Tree/Details, left region contains category hierarchy with items listed in a tree structure (ex:- Region-Countries-Locations-Departments in tree format) and right region contains the Employees list.In detail, Here User may drills down through categories using a tree until Employees are listed. Clicking the tree node name displays Employee list in the adjacent pane related to particular tree node. Implementation StepsThe script for creating the tables and inserting the data required for this application CreateSchema.sql Lets create a Java EE Web Application with Entities based on Regions, Countries, Locations, Departments and Employees table. Create a Stateless Session Bean and data control for the Stateless Session Bean. Add the below code to the session bean and expose the method in local/remote interface and generate a data control for that.Note:- Here in the below code "em" is a EntityManager. public List<Employees> empFilteredByTreeNode(String treeNodeType, String paramValue) { String queryString = null; try { if (treeNodeType == "null") { queryString = "select * from Employees emp ORDER BY emp.employee_id ASC"; } else if (Pattern.matches("[a-zA-Z]+[_]+[a-zA-Z]+[_]+[[0-9]+]+", treeNodeType)) { queryString = "select * from employees emp INNER JOIN departments dept\n" + "ON emp.department_id = dept.department_id JOIN locations loc\n" + "ON dept.location_id = loc.location_id JOIN countries cont\n" + "ON loc.country_id = cont.country_id JOIN regions reg\n" + "ON cont.region_id = reg.region_id and reg.region_name = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.contains("regionsFindAll_bc_countriesList_1")) { queryString = "select * from employees emp INNER JOIN departments dept \n" + "ON emp.department_id = dept.department_id JOIN locations loc \n" + "ON dept.location_id = loc.location_id JOIN countries cont \n" + "ON loc.country_id = cont.country_id and cont.country_name = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.contains("regionsFindAll_bc_locationsList_1")) { queryString = "select * from employees emp INNER JOIN departments dept ON emp.department_id = dept.department_id JOIN locations loc ON dept.location_id = loc.location_id and loc.city = '" + paramValue + "' ORDER BY emp.employee_id ASC"; } else if (treeNodeType.trim().contains("regionsFindAll_bc_departmentsList_1")) { queryString = "select * from Employees emp INNER JOIN Departments dept ON emp.DEPARTMENT_ID = dept.DEPARTMENT_ID and dept.DEPARTMENT_NAME = '" + paramValue + "'"; } } catch (NullPointerException e) { System.out.println(e.getMessage()); } return em.createNativeQuery(queryString, Employees.class).getResultList(); } In the ViewController project, create two ADF taskflow with page Fragments and name them as FirstTaskflow and SecondTaskflow respectively. Open FirstTaskflow,from component palette drop view(Page Fragment) name it as TreeList.jsff. Open SeconfTaskflow, from component palette drop view(Page Fragment) name it as EmpList.jsff and create two paramters in its overview parameters tab as shown in below image. Open TreeList.jsff , from data control palette drop regionsFindAll->Tree as ADF Tree. In Edit Tree Binding dialog, for Tree Level Rules select the display attributes as follows:-model.Regions - regionNamemodel.Countries - countryNamemodel.Locations - citymodel.Departments - departmentName In structure panel, click on af:Tree - t1 and select selectionListener with edit property. Create a "TreeBean" managed bean with scope as "session" as shown in below Image. Create new method as getTreeNodeSelectedValue and click ok. Open TreeBean managed bean and add the below code: private String treeNodeType; private String paramValue; public void getTreeNodeSelectedValue(SelectionEvent selectionEvent) { RichTree tree = (RichTree)selectionEvent.getSource(); RowKeySet addedSet = selectionEvent.getAddedSet(); Iterator i = addedSet.iterator(); TreeModel model = (TreeModel)tree.getValue(); model.setRowKey(i.next()); JUCtrlHierNodeBinding node = (JUCtrlHierNodeBinding)tree.getRowData(); //oracle.jbo.Row Row rw = node.getRow(); Object selectedTreeNode = node.getAttribute(0); Object treeListType = node.getBindings(); String treeNodeType = treeListType.toString(); this.setParamValue(selectedTreeNode.toString()); this.setTreeNodeType(treeNodeType); } public void setTreeNodeType(String treeNodeType) { this.treeNodeType = treeNodeType; } public String getTreeNodeType() { return treeNodeType; } public void setParamValue(String paramValue) { this.paramValue = paramValue; } public String getParamValue() { return paramValue; }<br /> Open EmpList.jsff , from data control palette drop empFilteredByTreeNode->Employees->Table as ADF Read-only Table. After selecting the  Employees result set, in Edit Action Binding dialog window pass the pageFlowScope parameters as shown in below Image. In empList.jsff page, click Binding tab and click on Create Executable binding and select Invoke action and follow as shown in below image. Edit executeEmpFiltered invoke action properties and set the Refresh to ifNeeded, So when ever the page needs the method will be executed. Create Main.jspx page with page template as Oracle Three Column Layout. Drop FirstTaskflow as Region in start facet and drop SecondTaskflow as Region in center facet, Edit task Flow Binding dialog window pass the Input Paramters as shown in below Image. Run the Main.jspx, tree will be displayed in left region and emp details will displyaed on the right region. Click on the Americas in tree node, all emp related to the Americas related will be displayed. Click on Americas->United States of America->South San Francisco->Accounting, only employee belongs to the Accounting department will be displayed.

    Read the article

  • What Extends JComponent?

    - by Geertjan
    Let NetBeans IDE tell you what extends JComponent: Thanks to Damian from Gdansk in Poland who left a comment in this blog yesterday that explains how to achieve the above: "Let's say you would like to find all implementations of TreeModel interface. I found today an answer: r-click on class/interface -> chose Navigate->Inspect Hierarchy->select second filter at the bottom of opened window or press Alt+Shift+F12 and then Alt+B." In the list above, double-click an item to open it in the NetBeans Java editor. Handy tip, dziekuje bardzo, Damian.

    Read the article

  • Dojo JsonRest store and dijit.Tree

    - by user1427712
    I'm having a some problem making JSonRest store and dijit.Tree with ForestModel. I've tried some combination of JsonRestStore and json data format following many tips on the web, with no success. At the end, taking example form here http://blog.respondify.se/2011/09/using-dijit-tree-with-the-new-dojo-object-store/ I've made up this simple page (I'm using dojotolkit 1.7.2) <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Tree Model Explorer</title> <script type="text/javascript"> djConfig = { parseOnLoad : true, isDebug : true, } </script> <script type="text/javascript" djConfig="parseOnLoad: true" src="lib/dojo/dojo.js"></script> <script type="text/javascript"> dojo.require("dojo.parser"); dojo.require("dijit.Tree"); dojo.require("dojo.store.JsonRest"); dojo.require("dojo.data.ObjectStore"); dojo.require("dijit.tree.ForestStoreModel"); dojo.addOnLoad(function() { var objectStore = new dojo.store.JsonRest({ target : "test.json", labelAttribute : "name", idAttribute: "id" }); var dataStore = new dojo.data.ObjectStore({ objectStore : objectStore }); var treeModel = new dijit.tree.ForestStoreModel({ store : dataStore, deferItemLoadingUntilExpand : true, rootLabel : "Subjects", query : { "id" : "*" }, childrenAttrs : [ "children" ] }); var tree = new dijit.Tree({ model : treeModel }, 'treeNode'); tree.startup(); }); </script> </head> <body> <div id="treeNode"></div> </body> </html> My rest service responds the following json { data: [ { "id": "PippoId", "name": "Pippo", "children": [] }, { "id": "PlutoId", "name": "Pluto", "children": [] }, { "id": "PaperinoId", "name": "Paperino", "children": [] } ]} I've tried also with the following response (actually my final intention n is to use lazy loading for the tree) { data: [ { "id": "PippoId", "name": "Pippo", "$ref": "author0", "children": true }, { "id": "PlutoId", "name": "Pluto", "$ref": "author1", "children": true }, { "id": "PaperinoId", "name": "Paperino", "$ref": "author2", "children": true } ]} Neither of the two works. I see no error message in firebug. I simply see the root "Subject" on the page. Thanks to anybody could help in some way.

    Read the article

  • Python ttk.Button -command, runs without button being pressed

    - by Markus Kothe
    I'm making a small script in python with ttk and I have a problem where a function runs where it shouldn't. The button code looks as follows: btReload = ttk.Button(treeBottomUI, text="Reload", width=17, command=loadModelTree(treeModel)) btReload.pack(side="left") and the function is as this: def loadModelTree(tree): print ("Loading models...") allModels = os.listdir(confModPath) for chunk in allModels: ... For some reason, the function runs without the button being pressed. Why?

    Read the article

  • Client side code snipets

    - by raghu.yadav
    function clientMethodCall(event) { component = event.getSource(); AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true); event.cancel(); } ]]-- <af:document>      <f:facet name="metaContainer">      <af:group>        <!--[CDATA[            <script>                function clientMethodCall(event) {                                       component = event.getSource();                    AdfCustomEvent.queue(component, "customEvent",{payload:component.getSubmittedValue()}, true);                                                     event.cancel();                                    }                 </script> ]]-->      </af:group>    </f:facet>      <af:form>        <af:panelformlayout>          <f:facet name="footer">          <af:inputtext label="Let me spy on you: Please enter your mail password">            <af:clientlistener method="clientMethodCall" type="keyUp">            <af:serverlistener type="customEvent" method="#{customBean.handleRequest}">          </af:serverlistener>bean code    public void handleRequest(ClientEvent event){                System.out.println("---"+event.getParameters().get("payload"));            } tree<af:tree id="tree1" value="#{bindings.DepartmentsView11.treeModel}" var="node" selectionlistener="#{bindings.DepartmentsView11.treeModel.makeCurrent}" rowselection="single">    <f:facet name="nodeStamp">      <af:outputtext value="#{node}">    </af:outputtext>    <af:clientlistener method="expandNode" type="selection">  </af:clientlistener></f:facet>   <f:facet name="metaContainer">        <af:group>          <!--[CDATA[            <script>                function expandNode(event){                    var _tree = event.getSource();                    rwKeySet = event.getAddedSet();                    var firstRowKey;                    for(rowKey in rwKeySet){                       firstRowKey  = rowKey;                        // we are interested in the first hit, so break out here                        break;                    }                    if (_tree.isPathExpanded(firstRowKey)){                         _tree.setDisclosedRowKey(firstRowKey,false);                    }                    else{                        _tree.setDisclosedRowKey(firstRowKey,true);                    }               }        </script> ]]-->        </af:group>      </f:facet>   </af:tree> </af:clientlistener></af:inputtext></f:facet></af:panelformlayout></af:form></af:document> bean code public void handleRequest(ClientEvent event){ System.out.println("---"+event.getParameters().get("payload")); } tree function expandNode(event){ var _tree = event.getSource(); rwKeySet = event.getAddedSet(); var firstRowKey; for(rowKey in rwKeySet){ firstRowKey = rowKey; // we are interested in the first hit, so break out here break; } if (_tree.isPathExpanded(firstRowKey)){ _tree.setDisclosedRowKey(firstRowKey,false); } else{ _tree.setDisclosedRowKey(firstRowKey,true); } } ]]--

    Read the article

  • How can I filter images and use filesystemview icons in my jtree?

    - by HoLeX
    First of all sorry about my english. So, i have some problems with my JTree because i want to filter specific types of images and also i want to use icons of FileSystemView class. Can you help me? I will appreciate so much. Here is my code: import java.awt.BorderLayout; import java.io.File; import java.util.Iterator; import java.util.Vector; import javax.swing.JPanel; import javax.swing.JTree; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; public class ArbolDirectorio extends JPanel { private JTree fileTree; private FileSystemModel fileSystemModel; public ArbolDirectorio(String directory) { this.setLayout(new BorderLayout()); this.fileSystemModel = new FileSystemModel(new File(directory)); this.fileTree = new JTree(fileSystemModel); this.fileTree.setEditable(true); this.fileTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent event) { File file = (File) fileTree.getLastSelectedPathComponent(); System.out.println(getFileDetails(file)); } }); this.add(fileTree, BorderLayout.CENTER); } private String getFileDetails(File file) { if (file == null) { return ""; } StringBuffer buffer = new StringBuffer(); buffer.append("Name: " + file.getName() + "\n"); buffer.append("Path: " + file.getPath() + "\n"); return buffer.toString(); } } class FileSystemModel implements TreeModel { private File root; private Vector listeners = new Vector(); public FileSystemModel(File rootDirectory) { root = rootDirectory; } @Override public Object getRoot() { return root; } @Override public Object getChild(Object parent, int index) { File directory = (File) parent; String[] children = directory.list(); return new TreeFile(directory, children[index]); } @Override public int getChildCount(Object parent) { File file = (File) parent; if (file.isDirectory()) { String[] fileList = file.list(); if (fileList != null) { return file.list().length; } } return 0; } @Override public boolean isLeaf(Object node) { File file = (File) node; return file.isFile(); } @Override public int getIndexOfChild(Object parent, Object child) { File directory = (File) parent; File file = (File) child; String[] children = directory.list(); for (int i = 0; i < children.length; i++) { if (file.getName().equals(children[i])) { return i; } } return -1; } @Override public void valueForPathChanged(TreePath path, Object value) { File oldFile = (File) path.getLastPathComponent(); String fileParentPath = oldFile.getParent(); String newFileName = (String) value; File targetFile = new File(fileParentPath, newFileName); oldFile.renameTo(targetFile); File parent = new File(fileParentPath); int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) }; Object[] changedChildren = { targetFile }; fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren); } private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) { TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children); Iterator iterator = listeners.iterator(); TreeModelListener listener = null; while (iterator.hasNext()) { listener = (TreeModelListener) iterator.next(); listener.treeNodesChanged(event); } } @Override public void addTreeModelListener(TreeModelListener listener) { listeners.add(listener); } @Override public void removeTreeModelListener(TreeModelListener listener) { listeners.remove(listener); } private class TreeFile extends File { public TreeFile(File parent, String child) { super(parent, child); } @Override public String toString() { return getName(); } } }

    Read the article

  • PyQt: How to keep QTreeView nodes correctly expanded after a sort

    - by taynaron
    I'm writing a simple test program using QTreeModel and QTreeView for a more complex project later on. In this simple program, I have data in groups which may be contracted or expanded, as one would expect in a QTreeView. The data may also be sorted by the various data columns (QTreeView.setSortingEnabled is True). Each tree item is a list of data, so the sort function implemented in the TreeModel class uses the built-in python list sort: self.layoutAboutToBeChanged.emit() self.rootItem.childItems.sort(key=lambda x: x.itemData[col], reverse=order) for item in self.rootItem.childItems: item.childItems.sort(key=lambda x: x.itemData[col], reverse=order) self.layoutChanged.emit() The problem is that whenever I change the sorting of the root's child items (the tree is only 2 levels deep, so this is the only level with children) the nodes aren't necessarily expanded as they were before. If I change the sorting back without expanding or collapsing anything, the nodes are expanded as before the sorting change. Can anyone explain to me what I'm doing wrong? I suspect it's something with not properly reassigning QModelIndex with the sorted nodes, but I'm not sure.

    Read the article

  • Colouring JTree's TreeNodes

    - by Amadan
    I have a JTree which I give objects that implement the TreeNode interface, and a custom TreeModel to display them (not using DefaultMutableTreeNode). I would like to change the text colour of some nodes. I can't find anything in the docs, except javax.swing.tree.DefaultTreeCellRenderer.setTextNonSelectionColor(Color newColor), but it will change everything indiscriminately, and I only need it for some nodes (specifically, broken links, i.e. nodes whose corresponding files can't be found on the disk, should be greyed out, the rest should be default). Can it be done, and how?

    Read the article

  • How to implement a tiered "selection tree" in Swing? (Or: is there an existing implementation?)

    - by Sbodd
    I need a Swing component that will let me display a tree-structured list of items, and allow the user to select or de-select an arbitrary subset of those items, with the ability to select or deselect an entire subtree's worth of components by picking that subtree's parent. (Basically, something similar to the Eclipse "Export JAR file's" dialog (an image of the relevant dialog is here - I basically want the "Select resources to export" component, but for a Swing application.) I know I can do this by creating a custom TreeCellRenderer, a custom TreeCellEditor, and a custom TreeModel - but that seems like an awful lot of work. Are there any good off-the-shelf implementations that I can use? Thanks!

    Read the article

  • New Sample Demonstrating the Traversing of Tree Bindings

    - by Duncan Mills
    A technique that I seem to use a fair amount, particularly in the construction of dynamic UIs is the use of a ADF Tree Binding to encode a multi-level master-detail relationship which is then expressed in the UI in some kind of looping form – usually a series of nested af:iterators, rather than the conventional tree or treetable. This technique exploits two features of the treebinding. First the fact that an treebinding can return both a collectionModel as well as a treeModel, this collectionModel can be used directly by an iterator. Secondly that the “rows” returned by the collectionModel themselves contain an attribute called .children. This attribute in turn gives access to a collection of all the children of that node which can also be iterated over. Putting this together you can represent the data encoded into a tree binding in all sorts of ways. As an example I’ve put together a very simple sample based on the HT schema and uploaded it to the ADF Sample project. It produces this UI: The important code is shown here for a Region -> Country -> Location Hierachy: <af:iterator id="i1" value="#{bindings.AllRegions.collectionModel}" var="rgn"> <af:showDetailHeader text="#{rgn.RegionName}" disclosed="true" id="sdh1"> <af:iterator id="i2" value="#{rgn.children}" var="cnty">     <af:showDetailHeader text="#{cnty.CountryName}" disclosed="true" id="sdh2">       <af:iterator id="i3" value="#{cnty.children}" var="loc">         <af:panelList id="pl1">         <af:outputText value="#{loc.City}" id="ot3"/>           </af:panelList>         </af:iterator>       </af:showDetailHeader>     </af:iterator>   </af:showDetailHeader> </af:iterator>  You can download the entire sample from here:

    Read the article

  • Reloading a JTree during runtime

    - by Patrick Kiernan
    I create a JTree and model for it out in a class separate to the GUI class. The data for the JTree is extracted from a file. Now in the GUI class the user can add files from the file system to an AWT list. After the user clicks on a file in the list I want the JTree to update. The variable name for the JTree is schemaTree. I have the following code for the when an item in the list is selected: private void schemaListItemStateChanged(java.awt.event.ItemEvent evt) { int selection = schemaList.getSelectedIndex(); File selectedFile = schemas.get(selection); long fileSize = selectedFile.length(); fileInfoLabel.setText("Size: " + fileSize + " bytes"); schemaParser = new XSDParser(selectedFile.getAbsolutePath()); TreeModel model = schemaParser.generateTreeModel(); schemaTree.setModel(model); } I've updated the code to correspond to the accepted answer. The JTree now updates correctly based on which file I select in the list.

    Read the article

  • How to highlight the new created file in JTree

    - by newbie123
    I want to make it like when I click a button, it will create a new file. Then the jTree will highlight the new file. Below are my code. Currently I create new file, i will show the new file but no highlight the file. class FileTreeModel implements TreeModel { private FileNode root; public FileTreeModel(String directory) { root = new FileNode(directory); } public Object getRoot() { return root; } public Object getChild(Object parent, int index) { FileNode parentNode = (FileNode) parent; return new FileNode(parentNode, parentNode.listFiles()[index].getName()); } public int getChildCount(Object parent) { FileNode parentNode = (FileNode) parent; if (parent == null || !parentNode.isDirectory() || parentNode.listFiles() == null) { return 0; } return parentNode.listFiles().length; } public boolean isLeaf(Object node) { return (getChildCount(node) == 0); } public int getIndexOfChild(Object parent, Object child) { FileNode parentNode = (FileNode) parent; FileNode childNode = (FileNode) child; return Arrays.asList(parentNode.list()).indexOf(childNode.getName()); } public void valueForPathChanged(TreePath path, Object newValue) { } public void addTreeModelListener(TreeModelListener l) { } public void removeTreeModelListener(TreeModelListener l) { } } class FileNode extends java.io.File { public FileNode(String directory) { super(directory); } public FileNode(FileNode parent, String child) { super(parent, child); } @Override public String toString() { return getName(); } } jTree = new JTree(); jTree.setBounds(new Rectangle(164, 66, 180, 421)); jTree.setBackground(SystemColor.inactiveCaptionBorder); jTree.setBorder(BorderFactory.createTitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, new Font("Arial", Font.BOLD, 12), new Color(0, 0, 0))); FileTreeModel model = new FileTreeModel(root); jTree.setRootVisible(false); jTree.setModel(model); expandAll(jTree); public void expandAll(JTree tree) { int row = 0; while (row < tree.getRowCount()) { tree.expandRow(row); row++; } }

    Read the article

  • JTree TreePath casting problem

    - by newbie123
    I got this casting problem java.lang.String cannot be cast to java.io.File, when I trying to do this TreePath p = new TreePath(new Object[] {"src","file","My Diary" }); This is my jtree file model class FileTreeModel implements TreeModel { private FileNode root; public FileTreeModel(String directory) { root = new FileNode(directory); } public Object getRoot() { return root; } public Object getChild(Object parent, int index) { FileNode parentNode = (FileNode) parent; return new FileNode(parentNode, parentNode.listFiles()[index].getName()); } public int getChildCount(Object parent) { FileNode parentNode = (FileNode) parent; if (parent == null || !parentNode.isDirectory() || parentNode.listFiles() == null) { return 0; } return parentNode.listFiles().length; } public boolean isLeaf(Object node) { return (getChildCount(node) == 0); } public int getIndexOfChild(Object parent, Object child) { FileNode parentNode = (FileNode) parent; FileNode childNode = (FileNode) child; return Arrays.asList(parentNode.list()).indexOf(childNode.getName()); } public void valueForPathChanged(TreePath path, Object newValue) { } public void addTreeModelListener(TreeModelListener l) { } public void removeTreeModelListener(TreeModelListener l) { } } class FileNode extends java.io.File { public FileNode(String directory) { super(directory); } public FileNode(FileNode parent, String child) { super(parent, child); } @Override public String toString() { return getName(); } }

    Read the article

  • How do I organize a GUI application for passing around events and for setting up reads from a shared resource

    - by Savanni D'Gerinel
    My tools involved here are GTK and Haskell. My questions are probably pretty trivial for anyone who has done significant GUI work, but I've been off in the equivalent of CGI applications for my whole career. I'm building an application that displays tabular data, displays the same data in a graph form, and has an edit field for both entering new data and for editing existing data. After asking about sharing resources, I decided that all of the data involved will be stored in an MVar so that every component can just read the current state from the MVar. All of that works, but now it is time for me to rearrange the application so that it can be interactive. With that in mind, I have three widgets: a TextView (for editing), a TreeView (for displaying the data), and a DrawingArea (for displaying the data as a graph). I THINK I need to do two things, and the core of my question is, are these the right things, or is there a better way. Thing the first: All event handlers, those functions that will be called any time a redisplay is needed, need to be written at a high level and then passed into the function that actually constructs the widget to begin with. For instance: drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: (DrawingArea -> IO ()) -> IO VBox createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do graphs <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 return hbox In this case, createStatView builds up a VBox that contains a DrawingArea to graph the data and potentially other widgets. It attaches drawStatData to the realize and exposeEvent events for the DrawingArea. I would do something similar for the TreeView, but I am not completely sure what since I have not yet done it and what I am thinking of would involve replacing the TreeModel every time the TreeView needs to be updated. My alternative to the above would be... drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: IO (VBox, DrawingArea) ... but in this case, I would arrange createUI like so: createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do (graphbox, graph) <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 on graph realize (drawStatData graph storeMVar field) on graph exposeEvent (do liftIO $ drawStatData graph storeMVar field return ()) return hbox I'm not sure which is better, but that does lead me to... Thing the second: it will be necessary for me to rig up an event system so that various events can send signals all the way to my widgets. I'm going to need a mediator of some kind to pass events around and to translate application-semantic events to the actual events that my widgets respond to. Is it better for me to pass my addressable widgets up the call stack to the level where the mediator lives, or to pass the mediator down the call stack and have the widgets register directly with it? So, in summary, my two questions: 1) pass widgets up the call stack to a global mediator, or pass the global mediator down and have the widgets register themselves to it? 2) pass my redraw functions to the builders and have the builders attach the redraw functions to the constructed widgets, or pass the constructed widgets back and have a higher level attach the redraw functions (and potentially link some widgets together)? Okay, and... 3) Books or wikis about GUI application architecture, preferably coherent architectures where people aren't arguing about minute details? The application in its current form (displays data but does not write data or allow for much interaction) is available at https://bitbucket.org/savannidgerinel/fitness . You can run the application by going to the root directory and typing runhaskell -isrc src/Main.hs data/ or... cabal build dist/build/fitness/fitness data/ You may need to install libraries, but cabal should tell you which ones.

    Read the article

1