void (ActionEvent event) { Object source = event.getSource(); if (source instanceof JTree tree) { TreePath path = tree.getLeadSelectionPath(); if (path != null) { if (tree.isExpanded(path)) { tree.collapsePath(path); } else { TreePath parent = path.getParentPath(); if (parent != null) { if (!tree.isRootVisible() && null == parent.getParentPath()) { int row = tree.getRowForPath(path); parent = row < 1 ? null : tree.getPathForRow(row - 1); } if (parent != null) { tree.setSelectionPath(parent); tree.scrollPathToVisible(parent); } } } } } }