2010-03-22 43 views
1

我有一个应用程序在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项目本身并提取这些数据的工具?我不介意是否有一些后处理步骤,因为手动输入是我唯一的选择。

+2

你是说你有JTree? – Wintermut3 2010-03-22 23:16:58

+0

我想出了两个可能的解释,并试图回答他们两个。希望至少有一个答案会有帮助。 :-) – 2010-03-25 02:40:53

+0

我假设应用程序有一个JTree,但我没有直接访问它。这可能需要Windows消息或类似的东西。 – User1 2010-03-26 14:20:02

回答

1

如果我们假设你有一个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

1

(我张贴第二个答案,这取决于问题的解释......)

如果你已经知道该怎么做,一旦你有一个JTree和你只是试图找到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; 
    } 
} 
:在任意 Container(包括任何 JComponentWindowJFrame等),然后将以下代码将搜索所述给定 Container,并返回找到的第一个 JTree(或 null如果没有 JTree可以找到)成分
相关问题