Google Tag Manager

2017/11/24

When JTree's node is expanded, collapse all other sibling nodes

Code

JTree tree = new JTree(makeModel());
tree.setRootVisible(false);
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
  private boolean isAdjusting;
  @Override public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {
    if (isAdjusting) {
      return;
    }
    isAdjusting = true;
    collapseFirstHierarchy(tree);
    tree.setSelectionPath(e.getPath());
    isAdjusting = false;
  }
  @Override public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException {
    //throw new ExpandVetoException(e, "Tree collapse cancelled");
  }
});
//...
public static void collapseFirstHierarchy(JTree tree) {
  TreeModel model = tree.getModel();
  DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
  Enumeration e = root.breadthFirstEnumeration();
  while (e.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
    boolean isOverFirstLevel = node.getLevel() > 1;
    if (isOverFirstLevel) { // Collapse only nodes in the first hierarchy
      return;
    } else if (node.isLeaf() || node.isRoot()) {
      continue;
    }
    tree.collapsePath(new TreePath(node.getPath()));
  }
}

References