I am trying to create a JTree in java swing now i want to change the node text at runtime
try
{
int a=1,b=2,c=3;
DefaultMutableTreeNode root =
new DefaultMutableTreeNode("A"+a);
DefaultMutableTreeNode child[]=new DefaultMutableTreeNode[1];
DefaultMutableTreeNode grandChild[]= new DefaultMutableTreeNode[1];
child[0] = new DefaultMutableTreeNode("Central Excise"+b);
grandChild[0]=new DefaultMutableTreeNode("CE Acts: "+c);
child[0].add(grandChild[0]);
root.add(child[0]);
tree = new JTree(root);
}
catch(Exception ex)
{
ex.printStackTrace()
}
Now i want later on how can i change A 1 to a 2 dynamically and similarly in child and grand child nodes
You are looking for javax.swing.tree.DefaultMutableTreeNode.setUserObject(Object)
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.setUserObject("My label");
model.nodeChanged(root);
This assumes that you are using the DefautltTreeModel
.
If you're not using a custom TreeModel, then the model of your tree is a DefaultTreeModel.
You'll need to walk the tree with some kind of comparator, given your DefaultMutableTreeNode getUserObject() (string or whatever) to achieve what you want.
You have 2 simple options accordingly to your question and the code that you pasted :
Upon successful changes, you'll need to fire events from the model that will trigger later a repaint of the view (nodesWereInserted, etc.).
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With