我已经阅读了很多已经提出的问题,但是还没有一个可靠的答案。我试图在jTree上设置选择,以尝试为我的Java项目创建一种API。我可以使用以下命令轻松地在父节点上设置选择:
myTree.setSelection(1);

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

//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;
    }

最佳答案

因此,解决方案最终变得很简单。我只需要使用Object数组创建一个新的TreePath(我没有做)。

因此,它看起来像:

TreeModel model = jTree1.getModel();
Object[] getNode = Walk(model, "sports", "basketball");
TreePath tPath = new TreePath(getNode);
jTree1.setSelectionPath(tPath);

09-30 15:34