Search code examples
javaswingjtree

change the jtree node text runtime


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


Solution

  • 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.