Results 1 to 3 of 3
  1. #1
    sergey is offline Member
    Join Date
    Oct 2009
    Rep Power

    Default How to display all TreePath's in JTree?

    I have JTree. I need to get all TreePath's from this jtree.
    Anybody knows how it can be done?

    Java Code:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root", true);
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child2");
    JTree jtree = new JTree(root);
    /*Here I need to get all TreePath's from jtree*/

  2. #2
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Pittsburgh, PA
    Rep Power


    I need to get all TreePath's from this jtree.
    The first response has to be, "Why?"
    It will usually be better to traverse the tree as needed
    instead of wasting the space on a list of the TreePaths.

    The second response has to be, "In what order?" There are many possibilities.
    These four combinations of DefaultMutableTreeNode methods can each
    traverse the tree:
    • breadthFirstEnumeration()
    • depthFirstEnumeration()
    • getChildCount()/getChildAt(int index)
    • getFirstChild()/getNextSibling()

    The third response will finally answer the question.
    Suppose you have chosen a breadth-first ordering. Then the code might be

    Java Code:
    [COLOR="DarkGreen"]// declare a Vector to store the result[/COLOR]
    Vector<TreePath> pathList = new Vector<TreePath>();  
    [COLOR="DarkGreen"]// get an enumeration that will visit every tree node
    [/COLOR]Enumeration pathGen = ((DefaultMutableTreeNode)jtree.getModel())
    [COLOR="DarkGreen"]// traverse the tree and add paths to pathList
    [/COLOR]while (pathGen.hasMoreElements()) {       
        // get an array of nodes from root to element
        TreeNode [] nodeArray = (TreeNode[])pathGen.nextElement();
        [COLOR="DarkGreen"]// wrap the array as a TreePath and append to list of paths[/COLOR]
        pathList.add(new TreePath(nodeArray));

  3. #3
    sergey is offline Member
    Join Date
    Oct 2009
    Rep Power

Similar Threads

  1. Move JTree item to another JTree.
    By Melki in forum AWT / Swing
    Replies: 8
    Last Post: 07-09-2009, 11:59 AM
  2. Replies: 1
    Last Post: 06-22-2009, 02:39 AM
  3. Replies: 8
    Last Post: 12-29-2008, 07:12 AM
  4. How to display a file system in a JTree view
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-27-2008, 07:43 PM
  5. how to display data in Jtree
    By paty in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 12:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts