Sorting a JTree's childrens

Please let me know how to sort a JTree (Sorting in alphabetical order).
Thanks.

Wen you insert node, insert it at correct place.
Store a Vector of all children in the node write a , write an Utility insert method, which does the binary search on the Vector and insertElementAt(positionResultOfBinarySearch).

Similar Messages

  • Sorting of JTree

    How to do sorting of JTree child names ?

    Thanks WalterLan it is working now.
    My next problem is how to sort tree nodes into two sets.
    My situation is: I have a JTree with 2 types of members: Primary, Secondary. I want sort tree so that all Primary Members comes into the tree first and then then secondary members. Root Node should be common.
    Thank you

  • How to load a directory in JTree with Children(On expansion)

    Hi,
    How can I load a Jtree directory with children on expanding the node of that directory.
    I have developed the following SSCCE. Please explain in its context.
    My specific question is, when you execute the code given here, you can see the file bb.1 inside the directory bb.
    bb.1 is a dummy which I used while creating the Jtree. When I expand bb, instead of the leaf bb.1 , I want to display some other file name, say qq.1 or jj.1.
    What should I do?
    Hope my question is clear(http://forums.sun.com/thread.jspa?threadID=5337544&start=20&tstart=0 -- please ignore the given link).
    //FileTreeFrame.java
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    public class FileTreeFrame extends JFrame {
      private JTree fileTree;
      private FileSystemModel fileSystemModel;
      public FileTreeFrame(String abc) {
        super("JTree FileSystem Viewer");
        // Build up your data
        List rootChildren = new ArrayList();
        rootChildren.add( new MyNode("aa") );
        List bbChildren = new ArrayList();
        bbChildren.add( new MyNode("bb.1") );
        rootChildren.add( new MyNode("bb", bbChildren) );
        rootChildren.add( new MyNode("cc") );
        MyNode rootNode = new MyNode("root", rootChildren);
        fileTree = new JTree(new FileSystemModel(new MyTreeNode(rootNode)));
        fileTree.setRootVisible(false);
        fileTree.setShowsRootHandles(true);
        getContentPane().add(fileTree);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
      public static void main(String args[]) {
        new FileTreeFrame("");
    class FileSystemModel extends DefaultTreeModel {
        public FileSystemModel(DefaultMutableTreeNode node) {
              super(node);
        public boolean isLeaf(Object node) {
              MyTreeNode treeNode = (MyTreeNode)node;
              return !((MyNode)treeNode.getUserObject()).hasChildren();
    =======================================================
    //MyNode.java
    import java.util.List;
    public class MyNode {
          private String name;
          private List children;
          public MyNode(String name) {
                this.name = name;
          public MyNode(String name, List children) {
                this.name = name;
                this.children = children;
          public boolean hasChildren() {
                return children!=null && children.size()>0;
          public String toString() {
                return name;
          public List getChildren() {
                return children;
    =========================================================
    //MyTreeNode.java
    import java.util.Iterator;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class MyTreeNode extends DefaultMutableTreeNode {
        public MyTreeNode(MyNode node) {
            super(node);
            addSubNodes();
        private void addSubNodes() {
              MyNode content = (MyNode)getUserObject();
              if (content!=null && content.hasChildren()) {
                    for (Iterator it = content.getChildren().iterator(); it.hasNext();) {
                          add( new MyTreeNode((MyNode)it.next()) );
    }

    I believe JFileChooser has a method setFileSelectionMode() which will allow you to do this. You can configure the chooser to allow selection of FILES_ONLY, DIRECTORIES_ONLY or FILES_AND_DIRECTORIES.
    I have not used this myself but understand it will achieve what you need.

  • Sort JTree alphabetical

    Hello everyone! I am trying to sort a JTree alphabetical. For the moment i made only the roots (partitions) to sort. I use the JTree to view all the partitions and view all the files. I override the interface TreeNode for my needs...and i made a class for cell renderer...
    public class FileTreeNode implements TreeNode
         public File file;
         private File[] children;     
         private  TreeNode parent;     
         public boolean isFileSystemRoot;     
         public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent)
              this.file = file;
              this.isFileSystemRoot = isFileSystemRoot;
              this.parent = parent;
              this.children = this.file.listFiles();
              if (this.children == null)
                   this.children = new File[0];
         public FileTreeNode(File[] children)
              this.file = null;
              this.parent = null;
              this.children = children;               
         @Override
         public Enumeration<?> children()
              final int elementCount = this.children.length;
              return new Enumeration<File>()
                   int count = 0;
                   public boolean hasMoreElements()
                        return this.count < elementCount;
                   public File nextElement()
                        if (this.count < elementCount)
                             return FileTreeNode.this.children[this.count++];
                        throw new NoSuchElementException("Vector Enumeration");
         @Override
         public boolean getAllowsChildren()
              return true;
         @Override
         public TreeNode getChildAt(int childIndex)
              return new FileTreeNode(this.children[childIndex],this.parent == null, this);
         @Override
         public int getChildCount()
              return this.children.length;
         @Override
         public int getIndex(TreeNode node)
              FileTreeNode ftn = (FileTreeNode) node;
              for (int i = 0; i < this.children.length; i++)
                   if (ftn.file.equals(this.children))
                        return i;                    
              return -1;
         @Override
         public TreeNode getParent()
              return this.parent;
         @Override
         public boolean isLeaf()
              return (this.getChildCount() == 0);
         public void sortRoots()
              List<File> list = Arrays.asList(this.children);
              Collections.sort(list);
              System.out.println("Partitions: " + list);
    and the other class....public class FileTreeCellRenderer extends DefaultTreeCellRenderer
         private static final long serialVersionUID = 1L;
         protected static FileSystemView fsv = FileSystemView.getFileSystemView();
         private Map<String, Icon> iconCache = new HashMap<String, Icon>();          
         private Map<File, String> rootNameCache = new HashMap<File, String>();     
         public Component getTreeCellRendererComponent(JTree tree, Object value,
                   boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)
              FileTreeNode ftn = (FileTreeNode) value;
              File file = ftn.file;
              String filename = "";
              if (file != null)
                   if (ftn.isFileSystemRoot)
                        filename = this.rootNameCache.get(file);
                        if (filename == null)
                             filename = fsv.getSystemDisplayName(file);                         
                             this.rootNameCache.put(file, filename);
                   else
                        filename = file.getName();
              JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
                        filename, selected, expanded, leaf, row, hasFocus);
              if (file != null)
                   Icon icon = this.iconCache.get(filename);
                   if (icon == null)
                        icon = fsv.getSystemIcon(file);
                        this.iconCache.put(filename, icon);
                   result.setIcon(icon);
              return result;
    and i run the application...File[] roots = File.listRoots();
    FileTreeNode rootTreeNode = new FileTreeNode(roots);
    tree = new JTree(rootTreeNode);
    tree.setCellRenderer(new FileTreeCellRenderer());
    can anyone please help me to sort alphabetical all the files from all the nodes...any help will be appreciated.
    Thanks.
    Calin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    might be easier if you were to add a small pictorial
    e.g. if you have a no-arg constructor JTree, you get this
    JTree
          colors
                   blue
                   violet
                   red
                   yellow
          sports
                   basketball
                   soccer
                   football
                   hockey
          food
                   hot dogs
                   pizza
                   ravioli
                   bananasnow put it how you would like it sorted

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

  • Sorting tree with Sortset/Treeset

    Have anyone tried sorting a jtrees nodes using sortset or treeset? I just want the children for each directory in my tree to be sorted. Collections like treeset and sortset should do the trick, but i have failed in my quest for the right solution.
    Can anyone please help me. I have been searching the forum, and there must be better ways of sorting a jtree than making large functions or subclasses..
    Thank you for helping me.
    Tobbmaister

    I have my own answer.
    When you build a tree, regardles if it's from a database, files og unix-enviroment, this will work.
    Gather all information in collections. For each parent( if you have any, get all children. ) ( this is before you start adding nodes to root.)
    use a while( children.hasNext ) and add one and one element to a TreeSort.
    When all children are in TreeSort, simlply use the getIterator method from TreeSort, and a sorted iterator will be returned.
    Use this iterator and add childrens to parent.
    This worked for me.

  • Sort generic XML document hierarchically ?

    Hi
    I need to sort entire xml alphabetically by node names.
    I.e. alphabetic sort by node names on first level, then alphabetic sort
    each node's children (second level), etc.
    The result will be same tree, but sorted alphabetically.
    I do not know names and structure beforehand, this is abstract XML document.
    Sorting can be applied either to text form , or DOM form (Document).
    Any Ideas ?
    Thanks !

    My idea would be to use the xsl:sort element ofXSLT.
    Thanks , but I can't figure out how to define such
    generic xsl:sort rule.
    All examples of this rule refers to tags by their
    name. And in my case tag name itself should be
    subject for sorting.Wouldn't that just be <xsl:sort select="name()">?
    In addition, this sorting should
    be performed on all levels of document , and depth is
    not known beforehand.So what? Put that in a template that's applied to every element. And make sure you call <xsl:apply-templates> in that template so it gets applied at all levels.

  • Can't mark thread as answered. ???

    Now this is interesting. I can edit my last post here: {thread:id=2519792} and mark it "Yes, my question has been answered." But when I save the message, it's not marked as answered.
    Why does it allow me to select "Yes" and then not save that selection? Maybe there are other things I was supposed to do, but it makes no mention of those, just goes about it business ignoring my selection. Sort of like what children do ...
    Howard

    Howard (... in Training) wrote:
    Now this is interesting. I can edit my last post here: {thread:id=2519792} and mark it "Yes, my question has been answered." But when I save the message, it's not marked as answered.
    Why does it allow me to select "Yes" and then not save that selection? Maybe there are other things I was supposed to do, but it makes no mention of those, just goes about it business ignoring my selection. Sort of like what children do ...Post questions relating to forum operation to the {forum:id=29} forum.

  • Diference between choice and message choice

    Hi
    I'm testing UIX. What is the diference between choice and message choice? When I can use this components?
    Thanks
    Liceth

    The messageChoice control is a combination of the choice and messageLayout controls. You can read about all the components in JDeveloper's help.
    The messageLayout control lays out a prompt, indexed children, end child, tip, and inline message (error message that displays below the choice, for example). Typically, the only indexed child of this bean will be a form element of some sort, but as many children as necessary can be added.
    The prompt can have an icon associated with the type of message. The bean's destination is attached to the icon to link to further information. It is also possible to indicate that user input is required.
    Clients can also add an "end" named child which will be rendered after the indexed children.
    To lay out multiple messageLayout beans the messageComponentLayout bean should be used. When messageLayout beans are placed inside a tableLayout or labeledFieldLayout the prompts will line up.
    Jeanne

  • Help needed - refuses to sleep on its own

    My 733mhz powerpc g4 refuses to sleep on its own even though the energy saver settings are correct. OS10.3.9. No bluetooth devices attached, standard keyboard, mouse and monitor. ADSK cable attached, and a printer, that's all. Who can help? Many thanks,
    Uli

    The workaround is to disconnect the cable before you want the Mac to sleep, and reconnect it when you want the computer awake.
    Some USB devices, and your printer is apparently one of them, have the annoying habit of asking the computer, "Daddy, are you still awake?" every minute or two, sort of like my children when they were two years old and I was supposedly reading them a bedtime story. Short of swatting it with a two-by-four or disconnecting it, there's nothing you can do to stop it.

  • Sorting contents of a JTREE

    Hi all..
    I have a Jtree that needs to be sorted. How can it do it fast and efficiently as the size of the tree can be huge. I have the tree contents that has depth of max 4 or 5. Your help on this is greatly appreciated.
    Thanks
    Srivarun

    Hi there ..
    You can sort the tree by again recreating the tree nodes.
      DefaultMutableTreeNode oldNodes = (DefaultMutableTreeNode)tree.getModel().getRoot();
      DefaultMutableTreeNode newNodes = new DefaultMutableTreeNode(oldNodes.getUserObject());
      void visitNodes(DefaultMutableTreeNode oldNodes,DefaultMutableTreeNode newNodes ){
        Vector sorted = sort(oldNodes.children());
        for (int i = 0; i < sorted.size(); i++)
          DefaultMutableTreeNode chNode = new DefaultMutableTreeNode(sorted.get(i));
          newNodes.add(chNode);
          visitNodes((DefaultMutableTreeNode)sorted.get(i),chNode);
      tree = new Tree(newNodes);hope this would help!
    or you can also checkout the thread .. http://forum.java.sun.com/thread.jsp?forum=57&thread=189640
    Regards,
    Asim

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

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

  • How to show only all children of selected node in JTree??

    Dear friends:
    I have Two Panels, PA and PB,
    PA has a Jtree as code below, and PB listens to PA,
    I hope to do following,
    If I select a node called A in PA, then Node A's all children such as A1, A2, A3 will be displayed in PB, but not display A1, A2, A3's children such as A3 has C1, C2, C3, C4 & C5, until I select A3 then PB will display only all A3's children: C1, C2, C3, C4 & C5;
    i.e, only populate each ONE level of children of Node A or any node I select, not its grandchildren and its grand-grand children;
    Please help how to do it??
    I tried amny times, failed.
    Thanks
    [1]. PA panel code:
    package com.atest;
         import java.awt.BorderLayout;
         import java.awt.event.MouseAdapter;
         import java.awt.event.MouseEvent;
         import java.util.Enumeration;
         import java.awt.Dimension;
         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.TreeModel;
         import javax.swing.tree.TreePath;
         public class DefaultMutableTreeMain extends JPanel {
         protected DefaultMutableTreeNode    top = new DefaultMutableTreeNode("Options");
         protected DefaultMutableTreeNode      selectedNode = null;
         protected final JTree tree;
         protected final JTextField jtf;
        protected Enumeration      vEnum = null;
         private      TreeModel                m;
         protected  DefaultMutableTreeNode      getDefaultMutableTreeNode()  {
              //textArea.getText();
                   return selectedNode;
         protected  DefaultMutableTreeNode setDefaultMutableTreeNode(DefaultMutableTreeNode tt)  {
              //textArea.getText();
                   selectedNode = tt;
                   return selectedNode;
         protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
         protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
           public DefaultMutableTreeMain() {
             setSize(300,300);
             setLayout(new BorderLayout());
             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 a3 = new DefaultMutableTreeNode("A3");
             a.add(a3);
             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);
             DefaultMutableTreeNode c = new DefaultMutableTreeNode("C");
             a3.add(c);
             DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("C1");
             c.add(c1);
             DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("C2");
             c.add(c2);
             DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C3");
             c.add(c3);
             DefaultMutableTreeNode c4 = new DefaultMutableTreeNode("C4");
             c.add(c4);
             DefaultMutableTreeNode c5 = new DefaultMutableTreeNode("C5");
             c.add(c5);
             tree = new JTree(top);
             JScrollPane jsp = new JScrollPane(tree);
             jsp.setPreferredSize(new Dimension(400,300));
             add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             add(jtf, BorderLayout.SOUTH);
               tree.addMouseListener(new MouseAdapter() {
               public void mouseClicked(MouseEvent me) {
                  TreePath   path = tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
                 setDefaultMutableTreeNode(selectedNode);
                     System.out.println("Current node selected is (tp.toString()=" + tp.toString());
                     System.out.println("Current node selected is getDefaultMutableTreeNode()=" + getDefaultMutableTreeNode());
                 if (tp != null){
                     jtf.setText(tp.toString());
                      System.out.println("It Has Children as selectedNode.getChildCount()= " + selectedNode.getChildCount());
                            Enumeration vEnum = selectedNode.children();
                                int i = 0;
                                while(vEnum.hasMoreElements()){
                                    System.out.println("2 selectedNode = " +  path.toString() + "  has " + i++ + " Children in vEnum.nextElement(" + i + ") = " + vEnum.nextElement());
                 else
                   jtf.setText("");
           public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.getContentPane().add(new DefaultMutableTreeMain());
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setSize(400, 400);
             frame.setVisible(true);
         }[2]. PB Panel code
    package com.atest;
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import javax.swing.JButton;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class DefaultMutableTreeSub extends JPanel implements java.io.Serializable{
      private JButton removeButton;
      private JButton addButton;
      JTree tree;
      private TreeModel      m;
      protected TreeDragSource ds;
      protected TreeDropTarget dt;
    protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
    protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
    protected DefaultTreeModel model;
    protected DefaultMutableTreeNode rootNode;
    DefaultMutableTreeMain dmm = null;
    JPanel inputPanel  = new JPanel();
      public JPanel SLTreeDNDEditableDynamic(DefaultMutableTreeMain tdnd ) {
        //super("Rearrangeable Tree");
        setSize(400,450);
        dmm = tdnd;
             setLayout(new BorderLayout());
             inputPanel.setLayout(new BorderLayout());
             JPanel outputPanel = new JPanel();
             System.out.println("Sub selectedNode tdnd= " + tdnd);
             tdnd.tree.addTreeSelectionListener(new TreeSelectionListener(){
                  public void valueChanged(TreeSelectionEvent evt){
                  TreePath[] paths = evt.getPaths();
                  TreePath   path = dmm.tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 DefaultMutableTreeNode itemNode = dmm.getDefaultMutableTreeNode();
                     System.out.println("Sub node selected is dmm.getDefaultMutableTreeNode()=" + dmm.getDefaultMutableTreeNode());
                  model = new DefaultTreeModel(itemNode);
                  tree = new JTree(model);
                  System.out.println("Sub selectedNode paths= " + paths);
                  System.out.println("Sub selectedNode path= " + path);
                  System.out.println("Sub selectedNode = " + selectedNode);
                  System.out.println("Sub itemNode = " + itemNode);
                  tree.putClientProperty("JTree.lineStyle", "Angled");
                  tree.setRootVisible(true);
                   inputPanel.add(new JScrollPane(tree),BorderLayout.CENTER);
             return inputPanel;
         public DefaultMutableTreeSub() {
              super();
    }thanks
    sunny

    Thanks so much, I use your code and import followig:
    import java.util.ArrayList;
    import java.awt.List;
    but
    private static List<Object> getChildNodes(JTree j) {
         Object parent = j.getLastSelectedPathComponent();
         int childNodeCount = j.getModel().getChildCount(parent);
         List<Object> results = new ArrayList()<Object>;
         for (i = 0; i < childNodeCount; i++) {
              results.add(parent, i);
         return results;
    here List<Object> and ArrayList()<Object> show red,
    Is my JDK version problem??
    my one is JKD
    C:\temp\swing>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    Error as follows:
    C:\temp\swing>javac DefaultMutableTreeSub.java
    DefaultMutableTreeSub.java:38: <identifier> expected
    private static List<Object> getChildNodes(JTree j) {
    ^
    1 error
    any idea??
    Thanks

  • JTree - Trying to make selection a parent select all children

    I have a jtree with checkboxes and titles. This is my first semester working with java, I started out in cpp so I'm pretty new to GUIs. I found an example of a Jtree with checkboxes on the leaf nodes online and was able to modify it to have checkboxes on all nodes.
    I have been reading through example code of JTrees but have not been able to figure out how to modify children when a parent is modified. If I clicked on an expandable node with sub nodes, I'd want all checkboxes under it to become checked. I've been trying to figure this out for a few days now.
    I tried adding a System.out to the getTreeCellEditorComponent class of the cell editor, to see if that's where I'm supposed to put the code (when i figure out what it is) but it gave unexpected output. Clicking a checkbox the first time called the println once, but after that, each click called println multiple times per click. I'm worried that having the extra calls to the code could mess things up. Where would I want to put code for it to be called only once per time the checkbox is clicked?
    Oh, I also tried adding a listener to the checkbox in the renderer but it gave really weird results too.
    How does the TreePath class work? I tried some stuff with getClosestPathForLocation but couldn't get anything to work.
    Thank you very much for your time and help.

    Thanks for pointing that out. I had tried a few others but yes his was very close to what I want. I just removed the node icons.
    Thanks

Maybe you are looking for

  • "Hot Folder to FTP" script review please

    I'm trying to make a folder on my Mac that is a "Hot Folder." I want this folder to have an action/script that as soon as it sees a new file added it will open Fetch and upload via mirror to an FTP folder. I was able to make the Fetch portion of the

  • Can't send mail os X 10.4.5

    since i set up my mail account I can recieve mail but i can't send it. There are 2 errors that pop up: This message culd not be delivered and will remain in your outbox until it can be delivered. +OK POP3 Ready pop2.netspace.net.au 0001c2a3 or This m

  • How to check standby is logical or physical

    Hi, can anybody let me know is there any query or any other way to get the information that the standby is an logical or physical DB version is oracle 9.2

  • Error in Cost Estimate through SAP t code CK11n

    Dear All, we are encountering a problem in the Production server with regards to the costing of the finished goods materials u201CFERTu201D, when cost estimate is ran through CK11N, the system pick up standard price maintianed in material master of R

  • Camera not working on MBA 13" mid 2012 with OS X 10.9.1

    The built-in camera is not being recognized by anything - Skype, FaceTime, PhotoBooth, you name it. There are no updates available and I've tried rebooting, so I have no idea what to do here. Does anyone have suggestions, please??