Java – Hide / filter nodes in JTree?

I have a data object in treemodel, and I want to show only a part of it in JTree - for argument, say leaves and their parents How to hide / filter unnecessary nodes?

Solution

My ultimate realization:

>There are two treemodels, the underlying one and the filtered one. > When the underlying treemodel changes, the filtered treemodel is regenerated from scratch Clone each node that should be visible and add it to the first visible ancestor (or root directory, if there is no visible ancestor) in the filtered treemodel See codez below, if you're curious > this has an unfortunate side effect, crashing every path the user opens To solve this problem, I added a treemodellistener to the filtered treemodel When the model changes, I will save the extended paths in JTree (using getexpandeddescendants()), and then re extend them (using swingutilities. Invoker())

I have to override equals () in the treenode class I'm using so that the new clone node is the same as the old clone node

...
  populateFilteredNode(unfilteredRoot,filteredRoot);
  ...

  void populateFilteredNode(TreeNode unfilteredNode,TreeNode filteredNode)
  {
    for (int i = 0; i < unfilteredNode.getChildCount(); i++)
    {
      TreeNode unfilteredChildNode = unfilteredNode.getChildAt(i);

      if (unfilteredChildNode.getType() == Type.INVISIBLE_FOLDER)
      {
        populateFilteredNode(unfilteredChildNode,filteredNode);
      }
      else
      {
        TreeNode filteredChildNode = unfilteredChildNode.clone();

        filteredNode.add(filteredChildNode);

        populateFilteredNode(unfilteredChildNode,filteredChildNode);
      }
    }
  }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>