Removes from a JTree model node all it's children and notifies model listeners. - Java Swing

Java examples for Swing:JTree

Description

Removes from a JTree model node all it's children and notifies model listeners.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import javax.swing.tree.TreeNode;

public class Main {
    /**//from   w  ww.ja va 2s.co  m
     * 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());
        }
    }
}

Related Tutorials