Search in JTree

To search for a node in my tree, given a path, I iterate over all the DefaultMutableTreeNodes starting at the root till I find nodes matching criteria and I walk down the tree.
Is there a better, more efficient way to search for tree nodes?
thx

no.
sun provides two methods:
DefaultMutableTreeNode.depthFirstEnumeration
or
DefaultMutableTreeNode.breadthFirstEnumeration
that's it
regards
testalucida

Similar Messages

  • Searching a jtree with string

    hi guys!
    i am searching a JTree with a "string"
    now i want to go the specific node (all expanded)
    by matching the string to the node
    how do i do it
    any suggestions
    thank u

    class FindAction extends KeyAdapter {
        private ModelTree               tree;
        private DefaultMutableTreeNode  found;
        private Enumeration             nodes;
        private Stack                   history;
        public FindAction(ModelTree tree) {
            this.tree = tree;
            found = null;
            history = new Stack();
        public void keyTyped(KeyEvent event) {
            String text = ((JTextField)event.getSource()).getText();
            switch (event.getKeyChar()) {
            case KeyEvent.VK_ENTER:
                if (text.equals("")) nodes = tree.topNode.preorderEnumeration();
                break;
            case KeyEvent.VK_BACK_SPACE:
                try {
                    TreePath path = (TreePath)history.pop();
                    tree.setSelectionPath(path);
                    tree.scrollPathToVisible(path);
                } catch (EmptyStackException ese) {}
                return;
            default:
                text += event.getKeyChar();
                if ((found != null) && found.toString().startsWith(text)) {
                    return;
                if (nodes == null) {
                    nodes = tree.topNode.preorderEnumeration();
                break;
            if ((found = find(text)) == null) {
                // try it one more time from the top
                nodes = tree.topNode.preorderEnumeration();
                found = find(text);
            try {
                TreePath path = new TreePath(found.getPath());
                tree.setSelectionPath(path);
                tree.scrollPathToVisible(path);
                history.push(path);
            } catch (NullPointerException e) {}
        private DefaultMutableTreeNode find(String searchString) {
            while (nodes.hasMoreElements()) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)nodes.nextElement();
                if (node.toString().startsWith(searchString)) {
                    return node;
            return null;
    }

  • Jtree search

    Hi, I use a JTree to read in a HTMLDocument and later want to search an element node in the JTree. I use JTree.indexof but it doesn't work. I also use a loop to search the JTree recursive using "equal" operator but it's still not working. Could someone please help me on this? When I use Eclipse debugger to examine the node, I notice there is a node id value match both in the JTree node and the search node. How can I get the node id? Any help is greatly appreciated. Thanks in advance.

    When comparing objects, the "equals" operates different than if you were comparing strings.
    Q: Why are they objects?
    A: All lists and trees default to objects so we aren't restricted to just strings! (You may want to add a Boolean or your own type!)
    Q: What is this id?
    A: From what I've seen, an object compares hash values, which are usually unique to each instance of the object. In short, it's a pseudo-random number that represents the object, so an object with the same name won't have the same value. (Think of a tree with more than once instance of "color" or "user")
    Q: How do we work around it?
    A: So you can do a few things, the post above is a great code example, or you can cast your objects to strings before comparing, such as *(String)nodeObject*, or nodeObject.toString();.
    For the record, my favorite solution is to make my own Objects in a new class, then override the "equals()" class, but that may be outside the scope of your project. :)
    Cheers.
    -Tres

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • JTree Expanded By Default

    Hi,
    I was wondering if there is a way to have a tree created and rendered in the completely expanded form. I am thinking along the lines that is there is a setting or a method that by default does it.
    If i am not mistaken there is a posting here in the forum to do this programatically.
    Thank You,
    -Uday

    Did you search for "JTree Expanded By Default" and saw that the answers were all about expanding the tree programatically:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=774838
    and you wanted to make double-sure there was no other way to do it?

  • JTree Selection

    I know this has been posted on the forum quite a lot and I have looked for it but I have not found any answers as of yet. Here is my delima. I am trying to refresh a JTree by removing the children from the root and then adding the new data. Having saved the selected path before I refresh the tree. I attempt to set it after I have reloaded the data. What sux is that I cannot get it to select the path that I perviously saved. Here is the code sample...
    public void refreshTree(BsxJTree _thingTree){
          AdminJTreeHelper helper = new AdminJTreeHelper(  );
          LinkedHashMap _treeData = helper.getTreeStructure(  );
          TreePath path  = _thingTree.getSelectionPath();
          DefaultMutableTreeNode node = (DefaultMutableTreeNode ).getLastPathComponent(  );
          DefaultTreeModel       model =  ( DefaultTreeModel ) _thingTree.getModel(  );
          DefaultMutableTreeNode root  = ( DefaultMutableTreeNode ) model.getRoot( );
          root.removeAllChildren(  );
         //uses the LinkedHashMap to load the tree
          populateTree( _treeData, _thingTree );
          _thingTree.expandToPath( node );
    }This is a method that I have written to extend the JTree
    //I know this code below  works b/c I have tested it.
        * Expands the tree to make the node visible.  This method beefs up the
        * expandPath method in JTree where it expandeds the path to the node
        * passed to it if it is expandable.  Otherwise if the node is not
        * expadable it will expand the nodes parent so that the node is
        * visible.  The node will then beselected.
        * @param node the node to expand to
        * @return the path what was expanded. Either the nodes path or the parents
        *         path.
       public TreePath expandToPath( DefaultMutableTreeNode node )
          TreePath path = new TreePath( node.getPath(  ) );
          if ( node.isLeaf(  ) )
             TreePath parentPath = path.getParentPath(  );
             expandPath( parentPath );
             setSelectionPath(path);
             return parentPath;
          else
             expandPath( path );
             setSelectionPath(path);
             return path;
       }

    for all of you that actually care... (those who are searching the forums for answers. I have created the following code which works to get the node which a userObject resides. Note this code can only be used when the JTree contains DefaultMutableTreeNodes (only nodes that a userObject can be attached).
    I use this code for refreshing a JTree and then reselecting the object that was selected prior to the refresh. Code is compilable.
    Thanks for all your help but I think I am going to award the duke dollars to my self on this one.
        * Searches the JTree for the for any UserObject that is equal to the passed
        * userObject.
        * <p>
        * <b>NOTE:</b>This only works when the tree nodes are
        * DefaultMutableTreeNodes.  Those are the only nodes that you can attach a
        * user object to.
        * </p>
        * Because most objects don't specify a  .equals(Object) method the objecs
        * are considered equal if they have the same toString() value.
        * @param userObject the object to find in the tree
        * @return the node that contains the userObject
       public DefaultMutableTreeNode findUserObject( Object userObject )
          TreeNode               root = ( TreeNode ) getModel(  ).getRoot(  );
          DefaultMutableTreeNode node = getUserObjectNode( root, userObject );
          if ( node == null )
             return null;
          else
             return node;
        * Visit all nodes in a tree and check to see if that node contains the
        * UserObject.  If the node is found return the tree path for the node.
        * @param node node to process
        * @param userObject JTree to search.
        * @return the node that contains the userObject
       private DefaultMutableTreeNode getUserObjectNode( TreeNode node,
                                                         Object userObject )
          // node is visited exactly once
          DefaultMutableTreeNode foundNode = null;
          if ( node instanceof DefaultMutableTreeNode )
             DefaultMutableTreeNode fn = ( DefaultMutableTreeNode ) node;
             String                 userObjectString = userObject.toString(  );
             String                 nodeObjectString = fn.getUserObject(  ).toString(  );
             if ( userObjectString.equals( nodeObjectString ) )
                return fn;
          if ( node.getChildCount(  ) >= 0 )
             for ( java.util.Enumeration e = node.children(  );
                      e.hasMoreElements(  ); )
                TreeNode n = ( TreeNode ) e.nextElement(  );
                foundNode = getUserObjectNode( n, userObject );
                if ( foundNode != null )
                   return foundNode;
          return null;
       }

  • Is it possible to add a JComponent as a JTree node? If yes then please help

    I am writing a java program in which I want to make my tree nodes editable by adding textfields, comboboxes, radiobuttons as nodes to the tree. So if anyone has any soluition please help!!!

    "Search Forums"
    has a wealth of information, and should be your first action when seeking a solution
    here's the results of searching, keywords: JTree JTextField
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=Jtree+JTextfield&subCat=&site=dev&dftab=&chooseCat=javaall&col=developer-forums
    plenty of the hits will have sample code you should be able to modify for your own needs

  • JTree setSelectionPaths problem

    Hi,
    I am searching my jTree and the value that are return by the search are stored. However I will like to be able to select all the nodes that match the criteria. I can select one node using setSelectedPath(node.getPath), however I would like to use the setSelectedPaths(TreePaths[]) method so that I can select all of the nodes that match the criteria. I would appreciate any help in this matter.
    Rudy

    No need to worry i sorted it.
    Thanks

  • How to search a child node in JTree

    Hi I am new to swings..
    My requirement is I have a Jsplit pane.
    I have search button with a text box in one and Jree in another pane.
    When I enter a string and hit Search button...It need to search the tree and expand that node highlight it.
    can anyone help in getting this done.

    public void actionPerformed(ActionEvent e)
      DefaultTreeModel m_model = new DefaultTreeModel(entityRoot);
      DefaultMutableTreeNode node = searchNode(m_searchText.getText());
      JTree m_tree = new JTree(m_model);
      TreePath root = m_tree.getPathForRow(0);
      searchTree(m_tree, root, m_searchText.getText());
    private void searchTree(JTree tree, TreePath path, String q)
    TreeNode node = (TreeNode)path.getLastPathComponent();
    if(node==null) return;
    if(node.toString().startsWith(q))
       tree.setScrollsOnExpand(true);
       tree.setSelectionPath(path);
    if(!node.isLeaf() && node.getChildCount()>=0)
       Enumeration e = node.children();
       while(e.hasMoreElements())
       searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
    }Edited by: EJP on 27/06/2011 09:53: added {noformat}{noformat} tags. Please use them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Good way to search JTree

    Hi,
    I have a JTree..and I need to search for a node in the tree by its name. For example if my tree is setup like this:
    root
    -----> FRUITS
    ----> apple
    ----> orange
    and i want to search for orange and retrieve the orange node, what is the best way to do this? I was thinking about starting from the root node, and recursively searching the tree comparing the names of the nodes to the nodeNameToSearchFor, if i find a match i return the node.....is there a better way of doing this??
    thanks.

    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.util.Enumeration;
    public class Test3 {
      public static void main(String[] arghs) {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)new JTree().getModel().getRoot();
        Enumeration enum = root.breadthFirstEnumeration();
        while (enum.hasMoreElements()) System.out.println(enum.nextElement());
    }

  • To search a node in a JTree in upward direction

    Hello,
    I am trying to implement a search functionality on a JTree. I need to:
    1. Search for the node in upward direction in a tree (from a current selected node).
    2. Search for the node in downward direction in a tree (from a current selected node).
    I am not able to write a logic which will search for the node in upward direction. Can anyone help me with the same?
    Thanks.

    For the upward search logic have you tried the public TreeNode[] getPathToRoot(TreeNode aNode) Look up the javadoc for this method, and you may get your solution.
    ~Debopam

  • Search dialog on JTree

    Hello,
    I am using JTree in our application I want to create search dialog for this tree, please can you help me??

    [How to Make Dialogs|http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html]

  • Search Jtree Problem (Easy Duke dollars)

    Hi all,
    I know that in order to find a node is a tree I can use getNextMatch method given by JTree. However, the problem here is that I want to serach for a child node and I don't know how to... for example...
    Root
    - Child 1
    - Child 2
    - Child 3
    If I search for the root node I would simply do
    getNextMatch("R",0,Position.Bias.Forward);But what if I want to search for Child 1 or Child 3? What would be in my search string?

    Hi,
    To search for a node in a JTree, you may use the breadthFirstEnumeration() method of the DefaultMutableTreeNode and then iterate through that enumeration until the desired node is found or the node is not found.
    You need to have a reference to the Root of the tree as a DefaultMutableTreeNode where the seacrh will begin.
    Let's say that the desired node's data = desiredElement
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(.....);
    java.util.Enumeration enum = root.breadthFirstEnumeration();
    while(enum.hasMoreElements())
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) enum.nextElement();
    if(node.getUserObject().equals(desiredElement))
    //you have found the node in the tree
    //you can get the parent using the getParent on this node as well
    //if you want the search path as well
    //if you reach here, the desired node is not in the tree
    mail me in case of problem : [email protected]

  • Jtree; searching node by inserting path name

    Hello,
    I have a jtree which allows me to explore my harddisk.
    The thing I want is finding a directory by inserting a path name ( with a JTextfield).
    I am already able to reveice the inserted path.
    But how do I let the JTree go to that inserted path name?
    For more information, just ask.
    Grtz

    well, if you have the node and are using DefaultTreeModel, you can call: getPathToRoot(TreeNode)
    Not sure how to find the node from the value except to just loop thru the entire tree... or maintain a separate table of value/node objects.

  • Search JTree for a node

    Hi everyone,
    Lets say I have a JTree such as:
    Root
    -Child1
    --Child1_1
    -Child2
    Now is there a method which given the name of a node, eg. Child1_1 can go and get that node? By get i mean i have the above tree then i say:
    currentNode = Child1_1;
    tree.getNode(currentNode);
    I know there are methods that can do this if the node has been selected but in my case it has to be done without the node being selected.
    Hope i've made it clear!
    Thanks.

    Hello.
    There is no such built-in method because it all depends on what kind of node you use. The String (name) representing a node is really a rendering thing.
    Assuming you're using a DefaultTreeModel with DefaultMutableTreeNodes :public static TreeNode findNode(JTree aTree, Object aUserObject) {
         if (aTree == null) throw new IllegalArgumentException("Passed tree is null");
         if (aUserObject == null) throw new IllegalArgumentException("Passed user object is null");
         DefaultMutableTreeNode node = (DefaultMutableTreeNode)aTree.getModel().getRoot();
         return findNodeImpl(node, aUserObject);
    private static DefaultMutableTreeNode findNodeImpl(DefaultMutableTreeNode aNode, Object aUserObject) {
         if (aNode.getUserObject().equals(aUserObject)) return aNode;
         int childCount = aNode.getChildCount();
         for (int i = 0; i < childCount; i++) {
              DefaultMutableTreeNode child = (DefaultMutableTreeNode)aNode.getChildAt(i);
              DefaultMutableTreeNode result = findNodeImpl(child, aUserObject);
              if (result != null) return result;
         return null;
    }

Maybe you are looking for

  • Mailing a link to a web page from safari freezes safari?

    iPad recently upgraded to iOS6, When attempting to email a link to a page, the email UI appears, I can enter an email address, but the send and cancel buttons are not responsive. I can exit Safari but I have to go to settings and clear cookies and da

  • Installing Production Premium CS6 - Prelude failed - exit code 6

    Hi Is this the official method for reporting installation problems of new applications? I have just installed Production Premium CS6 - I received an error message at the end (see below) that Prelude failed to install - All other apps installed ok Can

  • How do i enable cookies in safari

    How do I enable cookies in safri on a mac book pro?

  • Procedural confusion (several questions)

    My task is to develop a Course Management System: I have the desired variables for an abstract Course class which will be extended by 3 subclasses of CourseType Side: this task is due in 6 days and the how and why are becoming blurred At this time I

  • Music Videos HD in the iTunes Store.

    Hi everyone, Does anybody know why the music videos available for purchase in the iTunes Store aren't in HD ou full HD? Is there any reason for that? Thanks for any information.