隐藏/过滤JTree中的节点? [英] Hiding/filtering nodes in a JTree?

查看:149
本文介绍了隐藏/过滤JTree中的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以 TreeModel 表示的数据对象,我只想在我的 JTree中显示部分内容 - 为了争论,说叶子和他们的父母。如何隐藏/过滤不必要的节点?

I have a data object represented in a TreeModel, and I'd like to show only part of it in my JTree--for the sake of argument, say the leaves and their parents. How can I hide/filter the unnecessary nodes?

推荐答案

我的最终实施:


  • 有两个 TreeModel s,基础版和过滤版。

  • 当a更改发生在基础 TreeModel 上,从头开始重建已过滤的 TreeModel 。克隆应该可见的每个节点,并将其添加到已过滤的 TreeModel 中的第一个可见祖先(如果没有可见的话,则将其添加到根目录)。如果你很好奇,请参阅下面的代码。

  • 这会导致折叠用户打开的每个路径的不幸副作用。为了解决这个问题,我在过滤后的 TreeModel 中添加了 TreeModelListener 。当模型更改时,我将扩展路径保存在 JTree 中(使用 getExpandedDescendants()),然后重新展开他们以后(使用 SwingUtilities.invokeLater())。

  • Have two TreeModels, the underlying one and the filtered one.
  • When a change occurs on the underlying TreeModel, rebuild the filtered TreeModel from scratch. Clone each node that should be visible, and add it to its first visible ancestor in the filtered TreeModel (or the root if none are visible). See teh codez below, if you're curious.
  • This has the unfortunate side effect of collapsing every path the user had open. To get around this, I added a TreeModelListener to the filtered TreeModel. When the model changes, I save the expanded paths in the JTree (using getExpandedDescendants()), then re-expand them later (using SwingUtilities.invokeLater()).

我必须覆盖等于()在我使用的 TreeNode 类中,以便新的克隆节点与旧的克隆节点相同。

I had to override equals() in the TreeNode class I was using so that the new cloned nodes would be the same as the old cloned nodes.

  ...
  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);
      }
    }
  }

这篇关于隐藏/过滤JTree中的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆