我有一个使用 Java 编写的带有非常大的 TreeView 控件的应用程序。我想仅在叶子的类似 XPath 元素的列表(只是字符串而不是 JList)中获取树控件的内容。这是一个例子 根目录
|-Item1 |-Item1.1 |-Item1.1.1 (leaf) |-Item1.2 (leaf) |-Item2 |-Item2.1 (leaf)
将输出:
/Item1/Item1.1/Item1.1.1 /Item1/Item1.2 /Item2/Item2.1
我没有任何源代码或类似的东西。是否有我可以使用的工具来深入研究 Window 项目本身并提取这些数据?我不介意是否有一些后处理步骤,因为手动输入是我唯一的其他选择。
最佳答案
如果我们假设您有一个 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
。
关于java - 窃取另一个应用程序 TreeView 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2495541/