JTree搜索不搜索非扩展节点

时间:2017-05-16 04:24:49

标签: java swing search jtree

public final DefaultMutableTreeNode findNode(String searchString) {

    java.util.List<DefaultMutableTreeNode> searchNodes = getSearchNodes((DefaultMutableTreeNode)deviceTreeView.getModel().getRoot());
    DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)deviceTreeView.getLastSelectedPathComponent();

    DefaultMutableTreeNode foundNode = null;
    int bookmark = -1;

    if( currentNode != null ) {
        for(int index = 0; index < searchNodes.size(); index++) {
            if( searchNodes.get(index) == currentNode ) {
                bookmark = index;
                break;
            }
        }
    }

    for(int index = bookmark + 1; index < searchNodes.size(); index++) {    
        if(searchNodes.get(index).toString().toLowerCase().contains(searchString.toLowerCase())) {
            foundNode = searchNodes.get(index);
            break;
        }
    }

    if( foundNode == null ) {
        for(int index = 0; index <= bookmark; index++) {    
            if(searchNodes.get(index).toString().toLowerCase().contains(searchString.toLowerCase())) {
                foundNode = searchNodes.get(index);
                break;
            }
        }
    }
    return foundNode;
}   

private final java.util.List<DefaultMutableTreeNode> getSearchNodes(DefaultMutableTreeNode root) {
    java.util.List<DefaultMutableTreeNode> searchNodes = new java.util.ArrayList<DefaultMutableTreeNode>();

    java.util.Enumeration<?> e = root.preorderEnumeration();
    while(e.hasMoreElements()) {
        searchNodes.add((DefaultMutableTreeNode)e.nextElement());
    }
    return searchNodes;
}

它适用于2个级别,如果全部展开则可以工作。对于未展开的项目,它不会搜索深度是否超过2.

0 个答案:

没有答案