How to sort jTree Nodes

Hi,
I am interested in whats the easiest way to sort jTree Nodes alphabetically. Is there any Method to do this directly or may i use something like quicksort?
Thanks for help
Mirco

Thanks Hamed,
Well, I work in your code, and I post here.
  public static DefaultMutableTreeNode sortTree(DefaultMutableTreeNode root) {
                 for (int i =0; i<root.getChildCount()-1; i++) {
                          DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
                        String nt = node.getUserObject().toString();
                        for (int j=i+1;j<=root.getChildCount()-1;j++)
                                 DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j);
                                    String np = prevNode.getUserObject().toString();
                            System.out.println(nt+" "+np);
                            if (nt.compareToIgnoreCase(np)>0) {
                                           root.insert(node, j);
                                         root.insert(prevNode, i);
                        if (node.getChildCount() > 0) {
                    node = sortTree(node);
                 return root;
    }and this code I used after include in jtree
  public  void jTreeSortingBegin()
          dn = (DefaultMutableTreeNode)treeModel.getRoot();
          treeModel.reload();
          dn = sortTree(dn);
          treeModel.reload(dn);
    }for exemple
  addObject(jTextField1.getText());
        jTreeSortingBegin();

Similar Messages

  • How to sort Jtree node?

    Now, I want to sort tree node by increasing.
    for example there are three child node:
    [20 -40][
    10 - 20]
    [30- 60].
    they are added to JTree node by different order.but are shown in increasingorder.
    like this:
    [10 - 20]
    [20 -40][
    [30- 60].
    how to control tree node.

    Implement the Comparable interface in t he userobject class and possibly the toString(0 as well.
    Ex.
    public class UserObject implements java.lang.Comparable{
    public int compareTo(Object obj) throws ClassCastException
    public String toString()

  • How to change JTree nodes background?

    hello there
    i have a jtree which i set its background to red
    but the nodes background is still white
    why?and how to set the nodes background to red too?
    and how to remove the tree border
    because i tried setting it to null and it doesn't work?
    here is my code:
    package view;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.tree.*;
    class TreeComponent{
      public static void main(String[] args) {
        JFrame frame = new JFrame("Creating a JTree Component!");
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color", true);
        DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black");
        DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue");
        DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy Blue");
        DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark Blue");
        DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green");
        DefaultMutableTreeNode white = new DefaultMutableTreeNode("White");
        parent.add(black);
        parent.add(blue);
        blue.add(nBlue);
        blue.add(dBlue);
        parent.add(green );
        parent.add(white);
        JTree tree = new JTree(parent);
        tree.setBackground(Color.red);
        tree.setBorder(null);
        frame.add(tree);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        frame.setSize(200,200);
        frame.setVisible(true);
    }

    how to set the nodes background to red too?
    ((JComponent) tree.getCellRenderer()).setOpaque(true);[/code\
    how to remove the tree borderWhat border?
    db                                                                                                                                                                                                                                                                                                                                       

  • How to sort master-node in master-detail scenario without losing subnodes?

    Hi,
    I've a master-detail scenario and want to sort my master node.
    How can I sort the master node without losing the detail-subnodes?
    If I take a look in class CL_WDR_TABLE_METHOD_HNDL and method  IF_WD_TABLE_METHOD_HNDL~APPLY_SORTING
    Sorting is done by
    - unload node with context_node->get_static_attributes_table into an internal table
    - keeping node state like lead_selection(s) and attribute_properties
    - sort internal table
    - bind internal table to node
    - set lead_selection and properties
    But all subnodes are gone.
    How do you sort a master node?
    Thanks and Regards
    Carsten

    I think you have to write your own logic for that . May be you can implement IF_WD_TABLE_METHOD_HNDL in your class and extend the current logic to support subnodes.

  • How to set Jtree Nodes' name into TextField??

    Dear Sir:
    I have following code to select any file's name then put into TextField,
    see:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    public class JTreeSplitChooseDemo extends JPanel implements ActionListener{
        JFileChooser fc;
        JButton openButton, saveButton;
        JTextField jtf;
      public JTreeSplitChooseDemo() {
        final JTree tree;
        final JTextField jtf;
        JPanel jp= new JPanel();
        setPreferredSize(new Dimension(500,350));
        jp.setPreferredSize(new Dimension(500,300));
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
        DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
        top.add(a);
        DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
        a.add(a1);
        DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
        a.add(a2);
        DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
        top.add(b);
        DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
        b.add(b1);
        DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
        b.add(b2);
        DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
        b.add(b3);
        tree = new JTree(top);
        JScrollPane jsp = new JScrollPane(tree);
        jsp.setPreferredSize(new Dimension(500,300));
        tree.setPreferredSize(new Dimension(500,300));
        add(jsp, BorderLayout.CENTER);
        jtf = new JTextField("", 20);
        add(jtf, BorderLayout.SOUTH);
        tree.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
            if (tp != null)
              jtf.setText(tp.toString());
            else
              jtf.setText("");
      public JPanel JTreeText() {
             JPanel jp= new JPanel();
             JPanel jpanel= new JPanel();
             setPreferredSize(new Dimension(400,350));
             jp.setPreferredSize(new Dimension(400,300));
             JScrollPane jsp = new JScrollPane(jp);
             jsp.setPreferredSize(new Dimension(400,300));
             jpanel.add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             fc = new JFileChooser();
             openButton = new JButton("Open a File...",new ImageIcon("images/hui.gif"));
             openButton.addActionListener(this);
             JPanel buttonPanel = new JPanel(); //use FlowLayout
             buttonPanel.add(openButton);
             //jp.add(buttonPanel, BorderLayout.PAGE_START);
             jp.add(buttonPanel, BorderLayout.NORTH);
             jp.add(jtf, BorderLayout.CENTER);
             return jpanel;
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JTreeSplitChooseDemo(), new BorderLayout().WEST);
        frame.getContentPane().add(new JTreeSplitChooseDemo().JTreeText(), new BorderLayout().CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 350);
        frame.setVisible(true);
    @Override
    public void actionPerformed(ActionEvent e) {
         //Handle open button action.
        if (e.getSource() == openButton) {
          int returnVal = fc.showOpenDialog(JTreeSplitChooseDemo.this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
             jtf.setText(file.getName());
          } else {
             jtf.add("Open command cancelled by user.", null);
    }For example, If i choose file : C:\temp\ftp\TestMyFile.txt
    after I press open button, then choose it, then, the file name TestMyFile.txt will be displayed in the textFiled.
    My problem is that I hope to choose any node in the JTree on the left Panel, then when I choose it, this JNode I selected will be displayed its name in the TextField.
    Not file, I need choose JNode,
    ie, B1 under B node, or A1 under A node, then B1 will be displayed in jtf.
    How to do this one??
    Can Guru throw some light??
    Thanks
    sunny

    Thanks, camickr.
    My fault not to explain detail.
    Actually I mean that I will use a dialog box(very much look like a file choose) that is something like a file chooser then I can browse over JTree first for any node then I can choose or select a node in this JTree, after select this node, its name is populated into text field. My one is I will use a JTree browser (something like that) to get a tree node.
    ie, this showOpenDialog will browse over JTree, not File system.
    I did not want to click on the node then this node name is populated into textField.
    the sample (http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html) shows that when I select a node, then its name was populated to a destination.

  • How to highlight JTree node without selecting it

    Hello,
    I want to highlight a Tree Node without selecting it.
    Anybody having ideas as to how i can do it.
    thanks in advance.
    Reg,
    sai

    for what it's worth for anyone with the same problem, the problem was that the node was being regenerated as a different object so each time it went through the object wasn't the same and therefore had a new expanded value as default of false.

  • How-To Add JTree nodes on Expanding

    I'm connecting to a database to retrieve information for my JTree, but when I populate my JTree it takes forever due to the table size I'm extracting from. (Big tree). Is there a way to wait until someone opens a folder to add nodes to it?
    Thanks for any help.

    Hi, another way you can thing about is to create your own Userobject and if the valueChanged you can populate your userObject in the TreeSelectionListener.
    The only thing your UserObject must have a toString method. so you can implement a Method which is populating your Sub-Tree direct in your UserObject by invoking it from the TreeSelectionListener.
    With getLastSelectedPathComponent() you can get the point where you have to add your children
    if you have allowed children. This should also work without your own UserObjects.
    I hope this helps.
    Greetings Michael

  • Sorting the nodes of a JTree

    Can anyone tell me how to go about sorting the nodes in a JTree?

    The best way to do it is thru the treemodel. Either adjust the order in a DefaultTreeModel, or create your own TreeModel.

  • 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.

  • How to remove all nodes (except root node)from a Jtree?

    How to remove all nodes (except the root node)from a Jtree?

    Either:
    - remove all children of root.
    - save the root node, throws away the tree model, build a new TreeModel with the saved root, set the new TreeModel in the JTree.
    - implement your own TreeModel, which would support an emptyExceptRoot() method.
    IMHO, using the DefautlTreeModel and DefaultMutableTreeNode does lead to all sorts of small problems when the app evolves, and implementing your own TreeNode and TreeModel is not that hard and much more efficient.

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

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

  • How to get the icon type of a JTree node, very urgent

    hi,
    i need to get the type of a JTree node but don't know how. this is quite an emergency. please help. thank you all.
    -joey

    there are several icons defined in the DefaultTreeCellRenderer class, such as closedIcon, leafIcon, openIcon. i was wondering if there is any way to get the icon type of a node. thanks for your reply.
    -joey

  • How to get the TreePath of a JTree Node

    hello all:
    Given a DefaultMutableTreeNode JTree node, how i can
    get the TreePath for it.
    because I want to use this method to fire the function expandPath(TreePath path)
    thank you very much!
    -Daniel Mark

    thank you I had got idea from forum
    http://forum.java.sun.com/thread.jsp?forum=31&thread=381249
    thx again.
    -Daniel

  • How to post an Event (mouse left click) to JTree node

    Hi,
    I am using JTree for my application just like the windows explorer tree. By default, Jtree node will got focus using left click. But, I'd like that my tree will detect a right click so that I can copy any file to the Jtree. I've added a mouselistener to it but the node is not selected by the right click. Anyboby can teach me how to post a mouse left click event to the Jtree so that it will become selected using left click.
    Thanks a million

    See if this is useful
    public void mouseClicked(MouseEvent event)
    Object object = event.getSource();
    if (object == mTree)
    mTree_mouseClicked(event);
    private void mTree_mouseClicked(MouseEvent event)
    if(event.getModifiers()==event.BUTTON3_MASK)
    //your logic goes here
    }//close method

Maybe you are looking for