Java JTree get expansion state

Description

Java JTree get expansion state

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class Main {
   public static void main(String[] args) {
      DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      rootNode.add(a);/*from ww w  .  j a  v a2  s. c  o m*/

      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("2");
      a.add(a2);

      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      rootNode.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("1");
      b.add(b1);

      JTree tree = new JTree(rootNode);
      System.out.println(getExpansionState(tree, 0) );
      
      
      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new JScrollPane(tree));
      f.setSize(250, 250);
      f.setVisible(true);
   }
   public static String getExpansionState(JTree tree, int row) {
      TreePath rowPath = tree.getPathForRow(row);
      StringBuffer buf = new StringBuffer();
      int rowCount = tree.getRowCount();

      for (int i = row; i < rowCount; i++) {
          TreePath path = tree.getPathForRow(i);

          if ((i == row) || isDescendant(path, rowPath)) {
              if (tree.isExpanded(path)) {
                  buf.append("," + String.valueOf(i - row));
              }
          } else {
              break;
          }
      }

      return buf.toString();
   }
   public static boolean isDescendant(TreePath path1, TreePath path2) {
      int count1 = path1.getPathCount();
      int count2 = path2.getPathCount();

      if (count1 <= count2) {
          return false;
      }

      while (count1 != count2) {
          path1 = path1.getParentPath();

          count1--;
      }

      return path1.equals(path2);
  }
}



PreviousNext

Related