首页 > 解决方案 > 获取jtree的所有叶子

问题描述

在我的 jtree 中,我导入了一个包含 2 个包和 30 个类的项目 java。我会通过一个按钮添加所有这些类,但该代码不能完美运行,它只添加了 22 个类(叶子)。你能帮我吗,拜托 ^_^

btnG.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            TreeModel model = tree.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
             int packageCount = root.getChildCount();
             int  classCount=root.getLeafCount();

             for(int j = 0; j < classCount; j++){
                for(int i = 0; i < packageCount; i++){
                //------------------ package name-------------//
                String module = (String) root.getChildAt(i).getChildAt(j).toString();
                 String modulename = FilenameUtils.getBaseName(module);
                 System.out.println("----"+modulename+"***");
                //------------------ modules name-------------//
            }}
        }
    });

标签: java

解决方案


         int packageCount = root.getChildCount();
         int  classCount=root.getLeafCount();

         for(int j = 0; j < classCount; j++){
            for(int i = 0; i < packageCount; i++){

您不能为内部循环使用预定值。每个节点可以有不同数量的叶子。例如,一个包可能有 10 个类,而另一个包可能有 20 个类。

您需要编写一个通用循环,该循环仅根据每个节点中的子节点数进行迭代。

就像是:

TreeModel model = tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

for (int i = 0; i < root.getChildCount(); i++)
{
    DefaultMutableTreeNode child = (DefaultMutableTreeNode)root.getChildAt(i);
    System.out.println(child);

    for (int j = 0; j < child.getChildCount(); j++)
    {
        System.out.println("  - " + child.getChildAt(j));
    }
}

当然,这假设您只有两个级别的节点。

一个合适的解决方案是使用递归来遍历所有的孩子。


推荐阅读