Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get total number of nodes in a JTree?  RSS feed

 
Jack Wanes
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to get total number of nodes in a JTree, and cannot find a way to do it.
The current getRowCount() method returns the number of rows that are currently being displayed.
Is there a way to do this or I am missing something?

thanks,
 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should really be counting the nodes in the tree model. As you have seen, the GUI isn't a good place to try that.

And if you're using DefaultMutableTreeNode as your nodes, it's easy. Take the root node and call its breadthFirstEnumeration() method. This returns an Enumeration of all the nodes in some order which you don't care about. Read through it and count the nodes.
 
Rob Spoor
Sheriff
Posts: 20904
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And for any generic TreeModel, recursion is your friend:
After all, the number of nodes in a tree is 1 for the root plus the number of nodes of all sub trees.
 
Jack Wanes
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys for the hints.

Rob's impl works, just need to add childCount to count.
 
Rob Spoor
Sheriff
Posts: 20904
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure? Isn't that counting each child twice, as the count is starting out at 1? If you add childCount to count, then that adds to count the number of children. Inside the loop getNodeCount also returns at least 1 for each child.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!