我在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项目本身并提取这些数据?我不介意是否有一些后处理步骤,因为手动输入是我唯一的另一种选择。
答案 0 :(得分:1)
如果我们假设您有一个TreeModel
(您可以使用JTree
从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
语句,例如输出到文件或写入或附加到文件。 Writer
或StringBuilder
作为附加参数传递给这些方法。
答案 1 :(得分:1)
(我发布第二个答案,取决于问题的解释......)
如果您有JTree
后已经知道该怎么做,而您只是想在任意JTree
中找到Container
组件(包括任何JComponent
,Window
,JFrame
等),然后以下代码将搜索给定的Container
并返回它找到的第一个JTree
(如果没有,则返回null
可以找到JTree
):
/**
* Searches the component hierarchy of the given container and returns the
* first {@link javax.swing.JTree} that it finds.
*
* @param toSearch
* the container to search
* @return the first tree found under the given container, or <code>null</code>
* if no {@link javax.swing.JTree} could be found
*/
private JTree findTreeInContainer(Container toSearch) {
if (toSearch instanceof JTree) {
return (JTree)toSearch;
}
else {
for (final Component child : toSearch.getComponents()) {
if (child instanceof Container) {
JTree result = findTreeInContainer((Container)child);
if (result != null) {
return result;
}
}
}
return null;
}
}