java - 窃取另一个应用程序 TreeView 的内容

标签 java swing treeview windows-messages

我有一个使用 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 语句替换为其他内容,例如输出到文件或写入或附加到作为附加参数传递给这些方法的 WriterStringBuilder

关于java - 窃取另一个应用程序 TreeView 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2495541/

相关文章:

java - 滚动 listView 时 ListView 项目的背景变得困惑

java - 在哪里使用 Netbeans 本地化某些菜单项中的字符串?

python - tkinter Treeview 将 mysql 数据放入一列

html - 防止多级李横断

java - 如何使用 contains 从 Arraylist 中删除对象

java - 不应该出现的奇怪的 NumberFormatException?

java - 类和接口(interface)设计。方法未确定

java - 使用包含可编辑 JTextArea 的 JPanel 呈现 JTree 叶

Java Swing 使用文本文件中的数据填充多个 JTextField

javascript - 树表 - 在react.js上设置子项