简体   繁体   English

Java:如何检查String的整个JTree路径

[英]Java: How to check entire JTree paths for String

I have been looking at this for awhile now but I cant really seem to find much about it online. 我现在已经看了一段时间,但我似乎真的无法在网上找到它。 I have a JTree and a list of strings. 我有一个JTree和一个字符串列表。 I want to search just the lowest levels of the JTree(so not every node in the tree is searched, just the lowest nodes) for each of the strings and add the string to a list if the string i am searching for is present in the path of the lowest node 我想搜索每个字符串中最低级别的JTree(因此不会搜索树中的每个节点,只搜索最低节点),如果我要搜索的字符串存在于列表中,则将字符串添加到列表中最低节点的路径

something like this 这样的事情

public List<String> searchLowestNodes(List<String> wordsToSearchFor){
    List<String> matches = new ArrayList<>;
    for(String word: wordsToSearchFor){
        // i do not know how to get the lowest node for each path
        if(path.contains(word)){
            matches.add(word);
        }
        //keep looping for all paths
     }
     return matches;
}

Does anybody know how this can be done? 有谁知道如何做到这一点?

EDIT: Tree example 编辑:树的例子

Root
-assignment1
--paul
---example.java
--john
---example.java
-assignment2
--a2
---sean
----assignment.java
---mark
----assignment.java

so given the following tree it should only search the following paths for the words 因此,给定以下树,它应该只搜索以下路径的单词

root>assignment1>paul>example.java
root>assignment1>john>example.java
root>assignment2>a2>sean>assignment.java
root>assignment2>a2>mark>assignment.java

i do not want to add 我不想补充

root>assignment1
root>assignment1>paul
...

First, fetch the root of the tree model: 首先,获取树模型的根:

rootNode = (DefaultMutableTreeNode)tree.getModel().getRoot()

Now having this node, traverse the whole tree and store the leaves in your own data structure. 现在有了这个节点,遍历整个树并将叶子存储在您自己的数据结构中。 You can traverse the tree using rootNode.depthFirstEnumeration() , running through the enumerator and checking for each element element.isLeaf() . 您可以使用rootNode.depthFirstEnumeration()遍历树,运行枚举器并检查每个元素element.isLeaf()

After you have all the leaves, fetch their paths: element.getPath() . 获得所有叶子后,获取它们的路径: element.getPath() This gives you an array of nodes from the root to the leaf node. 这为您提供了从根节点到叶节点的节点数组。

Now you can do whatever you want with them. 现在你可以随心所欲地做任何事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM