如果我们假设您有一个TreeModel
(您可以从JTree
using获得JTree.getModel()
),那么以下代码将以您正在寻找的“/”分隔格式打印出树的叶子:
/**
* 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
语句替换为其他内容,例如输出到文件或写入或附加到传递给这些方法的 aWriter
或 aStringBuilder
作为附加论据。