1

我已经阅读了一堆已经提出的问题,但还没有看到一个可靠的答案。我正在尝试在 jTree 上设置选择,以尝试为我的 Java 项目创建一种 API。我可以很容易地在父节点上设置选择:myTree.setSelection(1);

有任何叶子离开子节点的问题。我有一个 walk 函数,我正在其中寻找一个特定的字符串。当我到达带有我正在寻找的字符串的节点时,我设法返回了一个 Object[]。但我无法将其转换为 Treepath 以使用 myTree.setSelectionPath(path)。有人可以帮忙吗?我很感激。

//My call
TreeModel model = jTree1.getModel();
        Object getNode = myWalk(model);
        jTree1.setSelectionPath((TreePath) getNode);
        //this throw an error stating that Object[] can't be converted to a path.  

public Object[] myWalk(TreeModel model, String s, String t){
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        DefaultMutableTreeNode child;
        TreeNode[] returnPath = null;
        int childrenCount = root.getChildCount();
        for(int i = 0; i < childrenCount; i++){
            child = (DefaultMutableTreeNode) root.getChildAt(i);
            if(child.toString().equals(s)){
                System.out.println(child.toString());
                int secondChildCount = child.getChildCount();
                DefaultMutableTreeNode secondLevelChild;
                for(int y = 0; y < secondChildCount; y++){
                    secondLevelChild = (DefaultMutableTreeNode) child.getChildAt(y);
                    if(secondLevelChild.toString().equals(t)){
                        System.out.println(secondLevelChild.toString());
                        returnPath = secondLevelChild.getPath();
                        //returnPath = new TreePath(new Object[] {root.toString(), child.toString(), secondLevelChild.toString()});
                    }
                }

            }


        }
        return returnPath;
    }
4

1 回答 1

2

所以解决方案最终很简单。我只需要使用和 Object 数组(我没有这样做)创建一个新的 TreePath。

所以它看起来像:

TreeModel model = jTree1.getModel();
Object[] getNode = Walk(model, "sports", "basketball");
TreePath tPath = new TreePath(getNode);
jTree1.setSelectionPath(tPath);
于 2017-07-19T19:52:19.403 回答