java - 获取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-------------//
}}
}
});
解决方案
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));
}
}
当然,这假设您只有两个级别的节点。
一个合适的解决方案是使用递归来遍历所有的孩子。
推荐阅读
- c# - 缺少 XML 序列化根元素
- mysql - MySQL加入字段列表中的未知列-不确定为什么它是未知的
- php - PHP htmlspecialchars() 或 htmlentities() 例外
- html - Django 日期和时间选择器
- php - 如何在 Wordpress 中禁用 HTTPS 并将 HTTPS 重定向到 HTTP?
- javascript - JavaScript - 用 async / await 替换 setTimeout
- apache-spark - 进行pyspark查询时如何提取json的值
- angular - ngClass 未检测到变量的变化
- azure - azure 数据湖 - 验证 csv 中的要求字段
- react-native - Gradle:无法初始化类 org.codehaus.groovy.runtime.InvokerHelper