如果我们假设你有一个TreeModel
(你可以使用JTree.getModel()
从JTree
得到),那么下面的代码会以你要查找的“/”分隔格式打印出树的叶子:
/**
* Prints the path to each leaf in the given tree to the console as a
* "/"-separated string.
*
* @param tree
* the tree to print
*/
private void printTreeLeaves(TreeModel tree) {
printTreeLeavesRecursive(tree, tree.getRoot(), new LinkedList<Object>());
}
/**
* Prints the path to each leaf in the given subtree of the given tree to
* the console as a "/"-separated string.
*
* @param tree
* the tree that is being printed
* @param node
* the root of the subtree to print
* @param path
* the path to the given node
*/
private void printTreeLeavesRecursive(TreeModel tree,
Object node,
List<Object> path) {
if (tree.getChildCount(node) == 0) {
for (final Object pathEntry : path) {
System.out.print("/");
System.out.print(pathEntry);
}
System.out.print("/");
System.out.println(node);
}
else {
for (int i = 0; i < tree.getChildCount(node); i++) {
final List<Object> nodePath = new LinkedList<Object>(path);
nodePath.add(node);
printTreeLeavesRecursive(tree,
tree.getChild(node, i),
nodePath);
}
}
}
当然,如果你不只想打印树的内容到控制台,你可以更换println
声明别的东西,如输出到文件或如写字或者附加到作为附加参数传递给这些方法的Writer
或StringBuilder
。
你是说你有JTree? – Wintermut3 2010-03-22 23:16:58
我想出了两个可能的解释,并试图回答他们两个。希望至少有一个答案会有帮助。 :-) – 2010-03-25 02:40:53
我假设应用程序有一个JTree,但我没有直接访问它。这可能需要Windows消息或类似的东西。 – User1 2010-03-26 14:20:02