Swing树模糊查询及定位

发布于 2018-07-18  512 次阅读


package com.Util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JTree;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FindInTree{
    public static void findInTree(JTree tree,String str){
        Object root = tree.getModel().getRoot();
        TreePath treePath = new TreePath(root);
        treePath = findInPath(tree,treePath, str);
        if (treePath != null) {
            tree.setSelectionPath(treePath);
            tree.scrollPathToVisible(treePath);
        }
    }
    
    private static TreePath findInPath(JTree tree,TreePath treePath, String str){
        Object object = treePath.getLastPathComponent();
        if (object == null) {
            return null;
        }
 
        String value = object.toString();
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(value);
        // 查找相应的字符串
        //if (str.equals(value)) {
        if(m.find()){
            return treePath;
        }else {
                    TreeModel model = tree.getModel();
                    int n = model.getChildCount(object);
                    for (int i = 0; i < n; i++) {
                        Object child = model.getChild(object, i);
                        TreePath path = treePath.pathByAddingChild(child);
         
                        path = findInPath(tree,path, str);
                        if (path != null) {
                            return path;
                        }
                    }
                    return null;
                }
            }
}

注:通过正则表达式匹配关键词和当前节点名称是否相同

 Pattern p = Pattern.compile(str);
 Matcher m = p.matcher(value);
 // 查找相应的字符串
m.find()


个人博客,用于记录工作日常的问题。