开发者

JTree Search Recursion Issue

开发者 https://www.devze.com 2023-04-12 05:51 出处:网络
I am new to using JTree, so please bear with me if I am overlooking some very basic things. I am working on a Jtree file explorer. It takes a directory, adds nodes, select nodes and all that good stuf

I am new to using JTree, so please bear with me if I am overlooking some very basic things. I am working on a Jtree file explorer. It takes a directory, adds nodes, select nodes and all that good stuff. The basics are done. The extra implementation includes giving the file/folder size of the selected node, which was pretty straightforward. But the problem lies in trying to search the tree. It recognizes that the file is present. But the recursion is repeating itself for some reason??? 开发者_开发百科And the value is not returning properly. I've included the two methods for reference. If there are reading relating to this, it will also be greatly appreciated.

public void searchTree(String find)
{
    TreePath root = tree.getPathForRow(0);

    System.out.println(search (root, find));
}


public String search (TreePath path, String find)
{
    TreeNode currentNode = (TreeNode)path.getLastPathComponent();

    String findPath = null;

    if (currentNode.isLeaf() && currentNode.toString().startsWith(find))
    {
            findPath = path.getPath()[path.getPath().length-2].toString() + File.separator + path.getPath()[path.getPath().length-1].toString();
            return findPath;  
    }

    if (!currentNode.isLeaf() && currentNode.getChildCount()> 0)
        for (int i = 0; i < currentNode.getChildCount(); i++)
                search(path.pathByAddingChild(currentNode.getChildAt(i)), find);

    return findPath;
}

To be more exact, the search output is appearing twice. What am I doing wrong???


So I realized that I was kinda sleep deprived and realized that the method was called twice by the initial creation of the tree. Don't know why this method was called twice though. But i tweaked the code a little and things are back to normal.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号