Java JTree remove all children from node

Description

Java JTree remove all children from node

import java.awt.Container;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

public class Main {
   public static void main(String args[]) {
      final JFrame f = new JFrame("JTree Demo");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new FlowLayout());
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
      DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("A");
      DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("B");
      DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C");
      root.add(c1);/* ww  w.  j  ava  2 s .  c  o  m*/
      root.add(c2);
      root.add(c3);

      c1.add(new DefaultMutableTreeNode("1"));
      c1.add(new DefaultMutableTreeNode("2"));

      c2.add(new DefaultMutableTreeNode("3"));
      c2.add(new DefaultMutableTreeNode("4"));

      c3.add(new DefaultMutableTreeNode("5"));
      DefaultMutableTreeNode n6 = new DefaultMutableTreeNode("6");

      c3.add(n6);

      JTree t = new JTree(root);

      removeAllChildren((DefaultTreeModel)t.getModel(),c3);
      

      c.add(new JScrollPane(t));
      f.pack();
      f.setVisible(true);
   }

   /**
    * Removes from a tree model node all it's children and notifies model
    * listeners.
    *
    * @param model model
    * @param node  a node of that model
    */
   public static void removeAllChildren(final DefaultTreeModel model,
           final DefaultMutableTreeNode node) {
       if (model == null) {
           throw new NullPointerException("model == null");
       }
       if (node == null) {
           throw new NullPointerException("node == null");
       }
       synchronized (model) {
           int count = node.getChildCount();
           List<TreeNode> children = new ArrayList<>(count);
           int[] indices = new int[count];
           for (int i = 0; i < count; i++) {
               children.add(node.getChildAt(i));
               indices[i] = i;
           }
           node.removeAllChildren();
           model.nodesWereRemoved(node, indices, children.toArray());
       }
   }
}



PreviousNext

Related