Java Swing How to - Expand selected Tree path








Question

We would like to know how to expand selected Tree path.

Answer

import java.util.HashMap;
import java.util.Stack;
/*w  w w  .  ja va 2  s  .c o m*/
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class Main extends Box {
  public Main() {
    super(BoxLayout.Y_AXIS);
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    for (int i = 0; i < 14; i++) {
      DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root" + i);
      node.add(new DefaultMutableTreeNode("Child" + i));
      root.add(node);
    }
    CustomTree tree = new CustomTree(root);
    tree.setRootVisible(false);
    JScrollPane pane = new JScrollPane(tree);
    add(pane);
    JButton button = new JButton("Expand");
    button.addActionListener(e-> tree.expandSelectedPaths());
    add(button);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main());
    frame.validate();
    frame.pack();
    frame.setVisible(true);
  }
}

class CustomTree extends JTree {
  HashMap<TreePath, Boolean> expandedState = new HashMap<TreePath, Boolean>();
  Stack<TreePath> s = new Stack<TreePath>();

  public CustomTree(DefaultMutableTreeNode root) {
    super(root);
  }
  public void expandSelectedPaths() {
    TreePath[] paths = getSelectionPaths();
    if(paths == null || paths.length == 0){
      return;
    }
    setSelectionPath(paths[0]);

    for (TreePath path : paths) {
      TreePath parentPath = path.getParentPath();

      while (parentPath != null) {
        if (isExpanded(parentPath)) {
          parentPath = null;
        } else {
          s.push(parentPath);
          parentPath = parentPath.getParentPath();
        }
      }

      for (int i = s.size() - 1; i >= 0; i--) {
        parentPath = s.pop();
        if (!isExpanded(parentPath)) {
          expandedState.put(parentPath, Boolean.TRUE);
        }
      }
    }

    if (accessibleContext != null) {
      ((AccessibleJTree) accessibleContext).fireVisibleDataPropertyChange();
    }

    for (TreePath path : paths) {
      fireTreeExpanded(path);
      try {
        fireTreeWillExpand(path);
      } catch (Exception eve) {
        return;
      }
    }
  }
}