Title: RE: managing slow-loading data in a JTree

>To improve the user experience, I'd like
>to immediately load enough data for the
>user to visually chew on for a while,
>then lazy load the rest of it (the lion's share).

>The javadoc for JTree.DynamicUtilTreeNode
>looks promising, but neither google nor this mail
>archive show many references to it.

>Is there a standard way to do this?

You can use that node class or your own.
A couple of key points you want to understand are:

* I'm assuming that you're using DefaultTreeModel and DefaultMutableTreeNode
  for your data -- either directly or via subclassing. 
  If not, you will have to solve similar problems in your classes

* you want to call DefaultTreeModel.setAsksAllowsChildren(true)
  This changes the protocol of isLeaf in the model.  This is a
  subtle but key aspect of DefaultTreeModel and it's interaction with JTree

* In your node class you have to two things:

  o lazily defer actual population until getChildCount() is called.
    If you've correctly set askAllowsChildren this won't be called until
    the user actually expands a node.
        private boolean _loaded = false;
        public int getChildCount() {
                if (!_loaded)
            {
                _loaded = true; // have to do this FIRST
                                // as add() calls back into this method

                loadData(); // your method to load content
            }
            return super.getChildCount();
        }
    Note: by rights you also need to do the same for children() but
          it's rarely a problem.

  o ensure that allowsChildren correctly states if you're a leaf or not
    BEFORE you have loaded your data.
    You can do this by setting the property or overriding -- whatever works
    for you. If you're not sure if its a leaf then return true.  If you've
    set askAllowsChildren on the model you will now get expansion handles
    before your data is loaded.

* If you can bring "chunks" of data down fast enough to be interactive then
  this scheme works well. If not you have to play some games (have the node
  say "loading..." until the data is there, etc)

* Spawning an async worker thread to keep loading data works well too.
 
* Just be careful about mutating your model outside the AWT thread as the
  Tree is a model listener.  Gather the data and use invokeLater to do the
  final mutation.

HTH
~rmp

Reply via email to