Pivot Tree List labels and lazy loading

Here’s how to lazy load a tree structure in pivot and supply nice(er) labels for all nodes.

1. Create a LabeledList that extends List

public class LabeledList extends ArrayList
{

private V label;

public LabeledList(V label)
{
    this.label = label;
}

public V getLabel()
{
    return label;
}

@Override
public boolean equals(Object o)
{
    return (o instanceof LabeledList && ((LabeledList) o).label.equals(label)
           && super.equals(o));
}

@Override
public int hashCode()
{
    int hash = 5;
    hash = 29 * hash + (this.label != null ? this.label.hashCode() : 0)
            + super.hashCode();
    return hash;
}
}
,v>

2. Create a simple renderer to display your new list

public class NodeTreeViewRenderer extends TreeViewNodeRenderer
{

 @Override
 public void render(Object o, Path path, int i, TreeView tv, boolean bln,
         boolean bln1, NodeCheckState ncs, boolean bln2, boolean bln3)
 {
     if (o != null && o instanceof LabeledList)
     {
         super.render(((LabeledList) o).getLabel(), path, i, tv,
                 bln, bln1, ncs, bln2, bln3);
     } else
     {
         super.render(o, path, i, tv, bln, bln1, ncs, bln2, bln3);
     }
 }
}

3. Put it together.

@WTKX TreeView myTree;
...
...
public void startup(Display display,
          Map map) throws Exception
  {
      ....
      List rootList = new arrayList();
      rootList.add(new LabeledList(new Date()));
      myTree.setData(rootList);
  },>,>

Now we have the problem of loading all the child nodes when the tree is expanded. This is handled by creating a TreeViewBranchListener and expanding LabeledList a little to track if it’s been loaded or not.

In LabeledList, add the following:

    private boolean loaded = false;

  public boolean isLoaded()
  {
      return loaded;
  }

  public void setLoaded(boolean loaded)
  {
      this.loaded = loaded;
  }

Now create the Listener

public class LazyLoadBranchListener implements TreeViewBranchListener
{
  public void branchExpanded(TreeView tv, Path path)
  {

      List currList = tv.getTreeData();

      for (Integer i : path)
      {
          currList = (List) currList.get(i);
      }

      LabeledList lList = (LabeledList) currList;

     if (!lList.isLoaded())
      {
          // load data for into lList. Add additional LabeledLists for directories or
          // straight objects for end nodes.
          // For long running loads, do the load in another thread
          lList.setLoaded(true);
      }
  }

  public void branchCollapsed(TreeView tv, Path path)
  {}
}

In your application class, add the new listener

    myTree.getTreeViewBranchListeners().add(new LazyLoadBranchListener());

One thought on “Pivot Tree List labels and lazy loading”

  1. Hi Mike,

    Great post. FYI, in your branchExpanded() method, you can cut a few lines out by simply saying:

    LabeledList lList = (LabeledList) Sequence.Tree.get(tv.getTreeData(), path);

Comments are closed.