3

在我看来,当我打电话时

JTree.expandPath( 路径 )

默认情况下,它的所有父级也会展开。但我真正想做的是,预先设置特定的隐形孩子进行扩展。这样当一个节点展开时,它的完整子树就会弹出。

我发现在 JTree 内部 expandedState.put(path, Boolean.TRUE);记录了扩展的节点,但我无法访问它。(ps我不想使用反射:)

为扩展事件安装监听器会导致大量运行时更新被触发。这就是为什么我更喜欢让 JTree 记录扩展状态。

希望还有其他方法可以做到。
任何帮助表示赞赏?

接受侦听器解决方案。选项 2

选项 1 覆盖:

一个讨厌的缺点..它取决于 setExpandedState() 的实现

private boolean cIsExpandingHidden = false;
private TreePath cExpandingPath;

public void expandBranchHidden(DefaultMutableTreeNode node) {
  TreeNode[] mPathSections = mNode.getPath();
  TreePath mPath = new TreePath(mPathSections);
  //
  if (!cTree.isVisible(mPath)){
    cIsExpandingHidden = true;
  }
  cExpandingPath = mPath;
  try{
    expandPath(mPath);
  }finally{
    cExpandingPath = null;
    cIsExpandingHidden = false;
  }
}

@Override
public boolean isExpanded(TreePath path) {
  // override the questions whether the node parents of
  //  'the currently expanded node' to return TRUE
  if (cIsExpandingHidden){
    if (path.isDescendant(cExpandingPath)){
      return true; // just claim it doesn't need expanding
    }
  }
  return super.isExpanded(path);
}

@Override
public void fireTreeExpanded(TreePath path) {
  // the treeUI must not to know.. bad luck for any other listeners 
  if (!cIsExpandingHidden){
    super.fireTreeExpanded(path);
  }
}

选项 2 监听器

/* code where new nodes are received */
{
  // only if direct parent is expanded.. else expansionListener will pick it up
  if (cTree.isExpanded(mCreator.getParentTreeNode())){
    for (TreeNode mNode : mAddNodes) {
      if (mNode.isDefaultExpanded()) {
        cTree.expandBranch(mNode);
        mNode.setDefaultExpanded(false);
      }
    }
  }
}

/*  expansion listener */
{
  if (cRecursiveExpand){
    return;
  }
  // walk through children, expand and clear its preference
  cRecursiveExpand = true;
  IExtendedTreeNode[] mNodes = cTree.getChildrenOfCurrentNode();
  for (IExtendedTreeNode mNode : mNodes) {
    TreeNode mTreeNode = (TreeNode)mNode;
    if (mTreeNode.isDefaultExpanded()){
      cTree.expandBranch(mTreeNode);
      mTreeNode.setDefaultExpanded(false);
    }
  }
  cRecursiveExpand = false;
}
4

2 回答 2

1

你会更容易打电话

addTreeExpansionListener(TreeExpansionListener tel)

treeExpanded(TreeExpansionEvent event) 调用 TreeExpansionListener 中的方法时,您可以检查是否应该为新扩展的 TreePath 递归扩展所有子级。

于 2009-10-20T15:21:24.543 回答
1

一种简单的方法是子类 JTree 并覆盖该方法

setExpandedState(TreePath path, boolean state)

在此方法中,不是扩展所有父级,而是仅扩展您要扩展的子路径。这正是该方法受到保护的原因:)

于 2009-10-21T06:52:46.610 回答