Reputation: 755
I've read through a bunch of questions already asked but haven't see an solid answer yet. I'm trying to set the selection on a jTree in an attempt to create a sort of API for my Java project. I can set selection on a parent node easily with say: myTree.setSelection(1);
Having trouble with any leafs off child nodes. I've have a walk function and I'm looking for a specific string in it. I've managed to return a Object[] when I reach the node with the string I'm looking for. But I can't convert it to a Treepath to use myTree.setSelectionPath(path). Can anyone help out with this? I appreciate it.
//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;
}
Upvotes: 1
Views: 4819
Reputation: 755
So the solution ended up being simple. I just need to create a new TreePath with and Object array (which I wasn't doing).
So it would look like:
TreeModel model = jTree1.getModel();
Object[] getNode = Walk(model, "sports", "basketball");
TreePath tPath = new TreePath(getNode);
jTree1.setSelectionPath(tPath);
Upvotes: 2