我使用JIDE's CheckBoxTree显示复选框的嵌套的树状结构,在这个例子中:如何计算JTree中的节点数?
我想知道树模型多少节点包含。
如果我打电话给方法tree.getModel().getChildCount(rootNode),我只能得到直接孩子的数量(例如在这种情况下为12),而不是任何孩子数量进一步嵌套(20+)。
我使用JIDE's CheckBoxTree显示复选框的嵌套的树状结构,在这个例子中:如何计算JTree中的节点数?
我想知道树模型多少节点包含。
如果我打电话给方法tree.getModel().getChildCount(rootNode),我只能得到直接孩子的数量(例如在这种情况下为12),而不是任何孩子数量进一步嵌套(20+)。
递归:
public int getNumberOfNodes(TreeModel model)
{
return getNumberOfNodes(model, model.getRoot());
}
private int getNumberOfNodes(TreeModel model, Object node)
{
int count = 1;
int nChildren = model.getChildcount(node);
for (int i = 0; i < nChildren; i++)
{
count += getNumberOfNodes(model, model.getChild(node, i));
}
return count;
}
非常优雅,辉煌,谢谢。 – Redandwhite
getChildcount应该是getChildCount('Count'的大写'c') – Blunderchips
遍历模型和计算:-)如果节点类型DefaultMutableTreeNode的,还有的API做。如果你是(使用SwingX的话)(任何机会:),它都有用于遍历任意模型的实用方法。否则,请查看代码并实施自己。 – kleopatra
您必须递归检查并计算所有节点。这种方式,你也可以忽略文件夹节点,如果你想 – moeTi