Java examples for Swing:JTree
Remove a TreeNode containing the specified obj from a JTree.
//package com.java2s; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeModel; public class Main { /**//from w ww . j ava2 s. co m * Remove a TreeNode containing the specified obj from a JTree. It is assumed * that all TreeNodes in the specified tree are DefaultMutableTreeNodes and its * TreeModel should be a DefaultTreeModel. * @param obj the contained * @param tree the JTree whose TreeNodes are DefaultMutableTreeNodes. */ public static void removeNode(Object obj, JTree tree) { DefaultMutableTreeNode treeNode = searchNode(obj, tree); DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); model.removeNodeFromParent(treeNode); } /** * Search a DefaultMutableTreeNode whose userObject is the specified obj. * @param obj the userObject. * @param tree the JTree whose TreeNodes are DefaultMutableTreeNodes. * @return a DefaultMuatbleTreeNode whose userObject is obj. */ public static DefaultMutableTreeNode searchNode(Object obj, JTree tree) { TreeModel model = tree.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model .getRoot(); if (root.getUserObject() == obj) return root; return searchNode(obj, root); } /** * A recursive method to search a DefaultMutableTreeNode that displays * an Object obj. */ public static DefaultMutableTreeNode searchNode(Object obj, DefaultMutableTreeNode parentNode) { DefaultMutableTreeNode treeNode = null; int size = parentNode.getChildCount(); // A list of nodes with children java.util.List parentNodes = new ArrayList(); for (int i = 0; i < size; i++) { treeNode = (DefaultMutableTreeNode) parentNode.getChildAt(i); if (treeNode.getUserObject() == obj) return treeNode; if (treeNode.getChildCount() > 0) parentNodes.add(treeNode); } for (Iterator it = parentNodes.iterator(); it.hasNext();) { treeNode = searchNode(obj, (DefaultMutableTreeNode) it.next()); if (treeNode != null) return treeNode; } return null; } }