JTree - sorting without collapsing

i have a JTree which represents data stored in my data layer. if this data changes, i do not only have to update the view part in the tree but also resort it to certain criteria. as far as well, this works fair enough, my problem is, that with every resorting, i remove/add children in the JTree which leads to structure changes. notifying them to the JTree results in the collapsing of all the branches under the event source. how can i prevent that? i'd like to just resort the nodes on one level and leave the collapse/expand of the nodes as it was.
tnx for the help!

Thanks for your advice, i tried that but it doesn't seem to work with my code, the effect stays the same. what do i have to change?
Note:
snippetComparator cmp = new MyComparator();
SortedSet sorted = new TreeSet(cmp);
sorted.addAll(this.children);
int i = 0;
for (Iterator it = sorted.iterator(); it.hasNext(); i++) {
DefaultMutableTreeNode element = (DefaultMutableTreeNode)it.next();
this.treeModel.removeNodeFromParent(element);
this.treeModel.insertNodeInto(element, this, i);
<<snippet
this is all i do, no manual creation of any TreeEvents.

Similar Messages

  • JTree refresh without collapsing my nodes

    Hello,
    I have a JTree using a custom TreeModel. I've also extended the TreeNode.
    What is the most elegant method to refresh the tree or only a node without
    collapsing the currently expanded nodes?
    Please note that there are multiple types of TreeNodes each representing
    a different object to display in the tree and contains an object that represents its
    value. Also the node has a method createChildren() to determine and create
    the child TreeNodes. Children are loaded from a business delegate. I need the
    tree to re-query the model (maybe for only one node) about the data and redisplay
    the changes without affecting the collapsed/expanded state of the nodes that
    are not changed (not supposed to refresh).
    My model actually asks the node for data like getChildsCount(), isLeaf() etc, etc.
    I'd like to say:
    myCustomNodeInstance.refresh();
    or
    myCustomTreeModelInstance.refresh(myCustomNodeInstance);
    and all nodes that are not children of myCustomNodeInstance to preserve
    their state.
    Thanx

    Did you try to call repaint() method on JTree ?

  • Add a node to JTree== view change without collapse

    I added a new node in a NodeTree structure.
    And I want to view changes in JTree, without collapse.
    What can I do?

    You need to add the clustered resource into vmm, and not the individual file servers. Its the clustered resource that moves between nodes of the cluster.

  • Restricting Jtree node from collapsing.

    Hi all,
    Is there any way by which i can restrict a Jtree node from collapsing?
    please help,
    thx,
    Soni.

    hi
    i got it,
    here is the solution
    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
    public void treeWillExpand(TreeExpansionEvent e)throws ExpandVetoException {
    public void treeWillCollapse(TreeExpansionEvent e)throws ExpandVetoException {
    TreePath p = e.getPath();
    DefaultMutableTreeNode n =
    (DefaultMutableTreeNode)p.getLastPathComponent();
    if (n == root) {
    throw new ExpandVetoException(e);
    -Soni

  • I sorted my worksheet and it saved the sort without asking if I wanted to save it!  How did this happen?

    I am on a mac mini OS X Yosemite using Numbers 3.5.2.
    I opened an existing spreadsheet, sorted one of the columns, then closed it out so I could open it and it would no longer be sorted (the sort screwed up all my headings), and the sort was saved!  Why did it save my sort without asking if I wanted to save the changes?

    Hi Julia,
    System Preferences > General > Ask to keep changes when closing documents
    This may recover the previous version:
    Regards,
    Ian.

  • Sorting JTree results in collapse of nodes!

    I've searched and searched and can not find a good example of how to do this. I've found many threads that pose the question with the only answer being something like "I figured it out, thanks anyway".
    My problem:
    I've got a tree, many nodes, many depths. I'd like to sort it. My present algorithm is to traverse the tree and sort the list of children of each node. Once I sort the children, obviously the indexes have changed, so you must correct them.
    I've tried:
    remove all children from the parent
    add the children in sorted order
    If I do that using something like parent.remove and parent.insert, thats fine as long as no children UNDER those children have been expanded. If they have, then I'm not accounting for them and thus the tree continues to show those children under the wrong nodes once the sorted nodes are added.
    If I do that using something like model.removeNodeFromParent and model.insertNodeInto, then the entire tree will collapse up to the node sorted on.
    Either way sucks!
    I've also tried passing Arrays.sort my own comparator that, depending on the compare outcome, will do the removeFromParent and insertNodeInto on the fly. This results in NOT collapsing the entire tree (probably because all nodes are never removed) however it seems like on a descending sort the nodes get messed up. I assumed this was because I was reordering them on the fly in the tree...but now that I'm thinking about it, maybe I was doing something else wrong.
    In any case, is there a standard proceedure for doing this? Why does it seem so difficult? I've spent a good two days on this. Crazy!

    Found this in another thread after all, might be my solution:
         public Vector savePaths() {
              Vector v = new Vector();
              for (int i=0; i<getTree().getRowCount(); i++) {
                   if (getTree().isExpanded(i)) {
                        v.add(getTree().getPathForRow(i));
              return v;
         public void loadPaths(Vector v) {
              for (int i=0; i><v.size(); i++) {          
                   getTree().expandPath((TreePath) v.get(i));
         }

  • Refreshing a JTree without collapsing

    I have a problem. I've seen a few topics on this issue but none helped.
    I try to refresh a tree and preserve the same structure (with the expanded nodes) after refreshing it. In order to do that i save all the expanded paths from the tree before refreshing it and trying to expand them again after refreshing (using expandPath() function). During refreshing all the nodes (but the root) are removed, then added again.
    Could anyone tell me what am i doing wrong?
    Thank you in advance,
    Claudia

    The nodes class extends DefaultMutableTreeNode, yes. Yes, the equal method is called.
    Here is the refresh method of the tree.
      public void refresh() {
        ArrayList expandedPaths = getExpandedPaths();
        ((MyTreeModel)getModel()).refresh(); // this method removes the nodes of the tree and readding them
        expandPaths(expandedPaths);
      public ArrayList getExpandedPaths() {
        ArrayList expandedPaths = new ArrayList();
        Enumeration enum = getExpandedDescendants(getPathForRow(0));
        while(enum != null && enum.hasMoreElements()) {
          TreePath tp = (TreePath)enum.nextElement();
          expandedPaths.add(tp);
        return expandedPaths;
      public void expandPaths(ArrayList pathlist) {
        for(int i = 0; i < pathlist.size(); i++) {
          expandPath((TreePath)pathlist.get(i));
      }

  • Problem with JTree while expanding/collapsing a node

    Hi,
    I'm using a JTree for displaying the file system.
    Here, i want that whenever a node get expanded,
    it should show the latest files/directories under that node.
    Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
    under that node and then creating a new node and adding it to parent (all in expand() method).
    But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
    resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
    i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
    Can anybody help me please...
    i got stuck b'coz of this only.
    Thanks...

    Now what i'm doing is every time expand() get called,
    i'm comparing all the children of that node in the
    current instance with all the children present in the
    file system (because there is a possibility that some
    file/dir may be added or deleted)
    is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
    b'coz right now i'm getting all the files/dirs that
    are newly added but facing some problem if somebody
    deletes a file/dir.
    i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
    or you could check if the file which a node represents exists and if not remove the node.
    thomas

  • Open items sorting without +/- sign

    Hi SAP GURU's,
    i would like to display the open items without +/- sign when i will try to sort. it is possible in edit options in while clearing. but when i will try to display the open items i can not get that option.
    Please send the solution as early as possible.
    your assistance will be highly appreciated.
    Regards,
    suresh konisetty.

    Suresh,
    Not possible w/o +/- sorting.

  • JTree Expand All & Collapse All...

    Hi All,
    i hv two buttons "Expand All" & "Collapse All". If i press "Expand All" i should expand all the nodes in the all the root nodes(JTree).
    If i press "Collapse All" i sh collapse all the entries in the JTree.
    Is there any way to acheive this.
    Thanks
    ss

    Hi!
    You can try these methods where treeRoot is the root node of the tree:
    * Collapses the function group tree.
    public void collapseAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.collapseRow(i);
    * Collapses the function group tree.
    public void expandAll() {
    for (int i = treeRoot.getChildCount(); i > 0; i--) {
    tree.expandRow(i);
    /Malin

  • JTree remove expand/collapse cross button...??

    Hi all,
    I have forbidden tree collapsing (by default it is fully expanded),
    and I want to remove expand/collapse cross buttons that actually are used to expand/collapse tree nodes.
    Is it possible and can anyone give me advice how i can do this.
    Thanks in advance.

    I tried extending the BasicTreeUI to return nulls for the collapsed and exapnded icons as shown in the code below. For the most part, it works great! However, one can still expand/collapse the tree by clicking on the point where the vertical and horizontal lines connect.
    I guess some one else will take over from here.
    import java.awt.BorderLayout;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.plaf.basic.BasicTreeUI;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Temp extends JFrame {
         private JTree tree = null;
         public Temp() {
              super("Test");
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              initComponents();
              pack();
              setVisible(true);
         private void initComponents() {
              DefaultMutableTreeNode rootNode =
                   new DefaultMutableTreeNode("User Preferences", true);
              DefaultMutableTreeNode connectionSettingsNode =
                   new DefaultMutableTreeNode("Connection Settings", true);
              DefaultMutableTreeNode sslNode =
                   new DefaultMutableTreeNode("SSL", false);
              DefaultMutableTreeNode firewallNode =
                   new DefaultMutableTreeNode("Firewall", false);
              DefaultMutableTreeNode securityNode =
                   new DefaultMutableTreeNode("Security", true);
              DefaultMutableTreeNode serverCertificatesNode =
                   new DefaultMutableTreeNode("Server Certificates", false);
              DefaultMutableTreeNode clientCertificatesNode =
                   new DefaultMutableTreeNode("Client Certificates", false);
              connectionSettingsNode.add(sslNode);
              connectionSettingsNode.add(firewallNode);
              securityNode.add(serverCertificatesNode);
              securityNode.add(clientCertificatesNode);
              rootNode.add(connectionSettingsNode);
              rootNode.add(securityNode);
              tree = new JTree(rootNode);
              JScrollPane scroller = new JScrollPane(tree);
              getContentPane().add(scroller, BorderLayout.CENTER);
              tree.setUI(new MyTreeUI());
              //tree.setShowsRootHandles(false);
         public static void main(String args []) {
              new Temp();
         class MyTreeUI extends BasicTreeUI {
              public Icon getCollapsedIcon() {
                   return null;
              public Icon getExpandedIcon() {
                   return null;
    }Sai Pullabhotla

  • JTree sorting problem, how to sort

    here is my code:
    DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
                             DefaultMutableTreeNode childone=new DefaultMutableTreeNode("id");
                             DefaultMutableTreeNode person1=new DefaultMutableTreeNode("david");
                             DefaultMutableTreeNode p11=new DefaultMutableTreeNode("java programming");
                             DefaultMutableTreeNode p12=new DefaultMutableTreeNode("maths");
                             DefaultMutableTreeNode p13=new DefaultMutableTreeNode("c programming");
                             person1.add(p11);
                             person1.add(p12);
                             person1.add(p13);
                             childone.add(person1);
                             DefaultMutableTreeNode person3=new DefaultMutableTreeNode("ann");
                             DefaultMutableTreeNode p31=new DefaultMutableTreeNode("georgian");
                             DefaultMutableTreeNode p32=new DefaultMutableTreeNode("english");
                             DefaultMutableTreeNode p33=new DefaultMutableTreeNode("russian");
                             person3.add(p31);
                             person3.add(p32);
                             person3.add(p33);
                             childone.add(person3);
                             DefaultMutableTreeNode person2=new DefaultMutableTreeNode("merab");
                             DefaultMutableTreeNode p21=new DefaultMutableTreeNode("veterinar");
                             DefaultMutableTreeNode p22=new DefaultMutableTreeNode("building");
                             person2.add(p21);
                             person2.add(p22);
                             childone.add(person2);
                             DefaultMutableTreeNode person4=new DefaultMutableTreeNode("maia");
                             DefaultMutableTreeNode p41=new DefaultMutableTreeNode("medicine");
                             DefaultMutableTreeNode p42=new DefaultMutableTreeNode("pediatri");
                             DefaultMutableTreeNode p43=new DefaultMutableTreeNode("aaaa");
                             p41.add(p42);
                             p41.add(p43);
                             person4.add(p41);
                             childone.add(person4);
                             DefaultMutableTreeNode childtwo=new DefaultMutableTreeNode("fullname");
                             DefaultMutableTreeNode c1=new DefaultMutableTreeNode("merab");
                             DefaultMutableTreeNode c2=new DefaultMutableTreeNode("maia");
                             DefaultMutableTreeNode c3=new DefaultMutableTreeNode("ann");
                             DefaultMutableTreeNode c4=new DefaultMutableTreeNode("david");
                             childtwo.add(c1);
                             childtwo.add(c2);
                             childtwo.add(c3);
                             childtwo.add(c4);
                             DefaultMutableTreeNode childthree=new DefaultMutableTreeNode("email");
                             DefaultMutableTreeNode d1=new DefaultMutableTreeNode("[email protected]");
                             DefaultMutableTreeNode d2=new DefaultMutableTreeNode("[email protected]");
                             DefaultMutableTreeNode d3=new DefaultMutableTreeNode("[email protected]");
                             childthree.add(d1);
                             childthree.add(d2);
                             childthree.add(d3);
                             root.add(childthree);
                             root.add(childone);
                             root.add(childthree);
                             jTree1 = new JTree(root);
                             jScrollPane1.setViewportView(jTree1);
                         //   DefaultTreeModel ddd=(DefaultTreeModel)jTree1.getModel();
                            Comparator<DefaultMutableTreeNode> comp=new Comparator<DefaultMutableTreeNode>() {
                                 public int compare(DefaultMutableTreeNode o1,DefaultMutableTreeNode o2) {
                                      return o1.toString().compareTo(o2.toString());
                            ArrayList<DefaultMutableTreeNode> arr=Collections.list(root.children());
                             Collections.sort(arr,comp);
                             root.removeAllChildren();
                            for(int i=0;i<arr.size();i++)
                                 root.add(arr.get(i));now i want to sort all nodes and leafs that contains this tree , how should i do that? can anyone correct this code so that it sorts all data in this jtree?

    We may extend DefaultMutableTreeNode to implement Comparable
    and override insert so that the relevant nodes are sorted after each insert:
    * TreeSort.java
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreeSort extends JFrame {
        private JTree jTree1;
        private JScrollPane jScrollPane1;
        public TreeSort() {
            super("TreeSort");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setSize(400,300);
            setLocationRelativeTo(null);
            MyNode root = new MyNode("root");
            MyNode childone = new MyNode("id");
            MyNode person1 = new MyNode("david");
            MyNode p11 = new MyNode("java programming");
            MyNode p12 = new MyNode("maths");
            MyNode p13 = new MyNode("c programming");
            person1.add(p11);
            person1.add(p12);
            person1.add(p13);
            childone.add(person1);
            MyNode person3 = new MyNode("ann");
            MyNode p31 = new MyNode("georgian");
            MyNode p32 = new MyNode("english");
            MyNode p33 = new MyNode("russian");
            person3.add(p31);
            person3.add(p32);
            person3.add(p33);
            childone.add(person3);
            MyNode person2 = new MyNode("merab");
            MyNode p21 = new MyNode("veterinar");
            MyNode p22 = new MyNode("building");
            person2.add(p21);
            person2.add(p22);
            childone.add(person2);
            MyNode person4 = new MyNode("maia");
            MyNode p41 = new MyNode("medicine");
            MyNode p42 = new MyNode("pediatri");
            MyNode p43 = new MyNode("aaaa");
            p41.add(p42);
            p41.add(p43);
            person4.add(p41);
            childone.add(person4);
            MyNode childtwo = new MyNode("fullname");
            MyNode c1 = new MyNode("merab");
            MyNode c2 = new MyNode("maia");
            MyNode c3 = new MyNode("ann");
            MyNode c4 = new MyNode("david");
            childtwo.add(c1);
            childtwo.add(c2);
            childtwo.add(c3);
            childtwo.add(c4);
            MyNode childthree = new MyNode("email");
            MyNode d1 = new MyNode("[email protected]");
            MyNode d2 = new MyNode("[email protected]");
            MyNode d3 = new MyNode("[email protected]");
            childthree.add(d1);
            childthree.add(d2);
            childthree.add(d3);
            root.add(childtwo);
            root.add(childone);
            root.add(childthree);
            jTree1 = new JTree(root);
            jScrollPane1 = new JScrollPane();
            jScrollPane1.setViewportView(jTree1);
            add(jScrollPane1);
        public static void main(final String[] args) {
            Runnable gui = new Runnable() {
                public void run() {
                    new TreeSort().setVisible(true);
            //GUI must start on EventDispatchThread:
            SwingUtilities.invokeLater(gui);
    class MyNode extends DefaultMutableTreeNode implements Comparable {
        public MyNode(String name) {
            super(name);
        @Override
        public void insert(final MutableTreeNode newChild, final int childIndex) {
            super.insert(newChild, childIndex);
            Collections.sort(this.children);
        public int compareTo(final Object o) {
            return this.toString().compareToIgnoreCase(o.toString());
    }Edited by: Andre_Uhres on Nov 22, 2008 3:47 PM
    There seems to be a small bug in your original code: childthree is added twice and childtwo isn't added at all.

  • Sorting without reloading the page

    Hi,
    I'd like to know how processing several sorting operations without reloading and ask the database each time the sorting of the elements is made.
    For that I guess a copy of the result tree obtained by the sql query, written in the xsql page, must be present in memory and always available for the several sorting processes (but is this a temporary xml document which is created? How handle and use this "copy"?). So, one and only one access to the database would be required.
    But I don't know how such a thing works?
    Thanks a lot to help me on this point.
    Bye

    You can easily do that by implementing the apex error handling function.
    See this working example http://apex.oracle.com/pls/apex/f?p=46417:10
    Login as test/test
    By default APEX shows an javascript alert message, I actually overwrote the native alert to show a message div using jquery
    function alert(message) {
    //    console.info(message);
    var msgBox = $('#msg-box');
      if (msgBox.length === 0) {
          msgBox = $('<div />', { 'id': 'msg-box'}).hide().prependTo('body');
      msgBox.html(message+' <a href="javascript:void(0);" onclick="$(\'#msg-box\').hide();">X</a>').fadeIn(500);
    }See {message:id=10735215}

  • Sorting without quering???

    Hello,
    is there any way that we can sort a block by a column without executing the query again...if yes then please tell me how can i achieve this,,
    I have a form based on view made on columns form three different tables having 5000 records and i have a button that sorts a particular column in ascending/descending order when pressed..
    I am currently uisng the execute_query et the end of my sorting code. and is taking 8 seconds to sort the block when the button is pressed.
    the block show 24 records at a time..
    I just want to know if there is any way that we can sort the data without quering again as the data is already in the form..and it will not take 8 seconds..
    thanks in advance
    regards,

    I do not query 5000 records on first execute query, only 24 records are
    retieved when the form runs and for 24 records it is still taking 8 seconds.Then something has gone wrong. Even if the server is doing a full-table-scan to order the 5000 records, then passing the first 24 to your form, that should only take about a second.
    Have you done something by mistake, like setting the block's Query All Records property to Yes, or maybe issued a Last_Record; command after the query?
    And how long does a similar query take in SQL Plus? You can test it this way:
    Declare
      Cursor C is
        -- this select should have the same where and order by as in your form:
        Select  col_1, colL_2, etc...
         from whatever_tables
         where ...
         order by col_A, col_B, etc... ;
      R C%rowtype;
    Begin
      Open C;
      for i in 1..24 loop
        Fetch C into R;
      end loop;
      Close C;
    End;
    /

  • Sorting without headers

    I am creating a book list and want to sort my columns without the headers. The header is sorted within my document.
    Help - thanks

    Look in that same forums "Questions and Answers" area. I already posted 2 & 3, Just posted Four last night. Starting work on 5 now.
    Numbers templates.com Forums
    Leave me feedback on what you think. I tried to make them short (5-10 pages each). So its an easy comfortable read. The whole book is about 30 pages right now.
    Using Pages as the word processor. Cmd-Shift-4 for screen shots. Nothing special beyond that.
    Hope you like the rest too... anyone else is invited to look at it too. Its free (my wife thinks we should publish when its done, maybe as an ebook) Your my 'Peer reviewers' and 'editors' I guess.
    Thanks,
    Jason

Maybe you are looking for

  • HT4623 My iPad will not allow me to download any apps

    My iPad will not let me download any apps, also in the APPS STORE it shows a '1' meaning that there is one new update, it will not even let me update.  Also when browsing some websites like BT, it shuts down and reverts back to the home page of all m

  • Invoking Xai Service from  BPEL process (Error 411--Length Required)

    Hi Friends, I am trying to invoke xai inbound service webserive i.e WSDL from BPEL process, when i am testing the request i am getting the following error oracle.sysman.emSDK.webservices.wsdlapi.SoapTestException: oracle.fabric.common.FabricInvocatio

  • Error occured in transferrules

    Hi,     I am extracting the 0material data from r/3 to bw side.after replicating datasources.i will attached to infosource. next when we double click on infopackage saying transferrules are inactive.when iam activating that transfer rules the error w

  • Compressor job controller, compressor trancoder

    After quitting FCP7 my computer refuses to stay in sleep mode. Consulting Activity Monitor, I see that the above mentioned two processes are in red, and I have to force quit them. Are these things related, and is there a fix?

  • How to paste a Word table into email without showing the guidelines.

    When I paste a Word table into an email using Explorer, the guidelines don't show. When I paste into an email while using Firefox, the lines show. I don't want the guidelines to show.