How to Remove Node from JTree
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   saumil_shah
Posted On:   Tuesday, April 9, 2002 03:07 AM

I want to remove the Node from JTree,on some event.
Pl. Provide me solution urgent.

Re: How to Remove Node from JTree

Posted By:   Lee_Meador  
Posted On:   Wednesday, April 10, 2002 07:15 AM

It is going to depend on how you did the TreeModel. Here are some what-if's:



If you are using DefaultTreeModel with DefaultMutableTreeNode nodes, you find the node you want to remove (call it 'node'), which is a DefaultMutableTreeNode and do something like the code below:



Object[] path = ((DefaultMutableTreeNode)node.getParent()).getPath(); // You can build this path yourself

int[] childIndices = new int[1];
childIndices[0] = node.getParent().getIndexInParent(node); // index of removed node (before being removed)

Object[] children = new Object[1];
children[0] = node; // the removed node

node.removeFromParent(); // take out the node from the tree.

tree.getModel().fireTreeNodesRemoved(this, path, childIndices, children); // Fire the change event


If you are using some other TreeModel, the principle is the same.



  1. Find the path to the parent of the node being removed.
  2. Find the index of the removed node/object in that parent's children
  3. You know the object being removed 4) remove the object you want to remove from whereever it is stored. Do so in a way that it will not be retreived by the TreeModel in the future.
  4. Issue a TreeModelEvent to all listeners attached to the TreeModel. Call their 'treeModelRemoved' method with the TreeModelEvent build from the information in 1, 2 and 3.

Without more information about your jtree, that's vague, but the best I can do.

About | Sitemap | Contact