1

我在 Java 中有一个非常大的 TreeView 控件的应用程序。我只想在叶子的 XPath 类元素的列表(只是字符串而不是 JList)中获取树控件的内容。这是一个示例根

|-项目1
  |-Item1.1
    |-Item1.1.1(叶子)
  |-Item1.2(叶)
|-项目2
  |-Item2.1(叶)

会输出:

/Item1/Item1.1/Item1.1.1
/Item1/Item1.2
/Item2/Item2.1

我没有任何源代码或任何类似的方便的东西。有没有我可以用来挖掘 Window 项目本身并提取这些数据的工具?我不介意是否有一些后处理步骤,因为手动输入是我唯一的选择。

4

2 回答 2

1

(我发布第二个答案,具体取决于问题的解释......)

如果您已经知道一旦有了 a 之后该做什么,JTree并且您只是想JTree任意查找组件Container(包括任何JComponentWindowJFrame等),那么以下代码将搜索给定的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;
    }
}
于 2010-03-25T02:40:07.517 回答
1

如果我们假设您有一个TreeModel(您可以从JTreeusing获得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作为附加论据。

于 2010-03-25T02:27:16.617 回答