David Koelle David Koelle - 13 days ago 5
Java Question

Java TreeNode: How to prevent getChildCount from doing expensive operation?

I'm writing a Java Tree in which tree nodes could have children that take a long time to compute (in this case, it's a file system, where there may be network timeouts that prevent getting a list of files from an attached drive).

The problem I'm finding is this:


  1. getChildCount()
    is called before the user specifically requests opening a particular branch of the tree. I believe this is done so the
    JTree
    knows whether to show a + icon next to the node.

  2. An accurate count of children from
    getChildCount()
    would need to perform the potentially expensive operation

  3. If I fake the value of
    getChildCount()
    , the tree only allocates space for that many child nodes before asking for an enumeration of the children. (If I return '1', I'll only see 1 child listed, despite that there are more)



The enumeration of the children can be expensive and time-consuming, I'm okay with that. But I'm not okay with
getChildCount()
needing to know the exact number of children.

Any way I can work around this?

Added: The other problem is that if one of the nodes represents a floppy drive (how archaic!), the drive will be polled before the user asks for its files; if there's no disk in the drive, this results in a system error.

Update: Unfortunately, implementing the
TreeWillExpand
listener isn't the solution. That can allow you to veto an expansion, but the number of nodes shown is still restricted by the value returned by
TreeNode.getChildCount()
.

Answer

There are a few parts to the solution:

  • Like Lorenzo Boccaccia said, use the TreeWillExpandListener

  • Also, need to call nodesWereInserted on the tree, so the proper number of nodes will be displayed. See this code

  • I have determined that if you don't know the child count, TreeNode.getChildCount() needs to return at least 1 (it can't return 0)