adesh singh
adesh singh

Reputation: 1727

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

Upvotes: 4

Views: 13927

Answers (2)

Guillaume Polet
Guillaume Polet

Reputation: 47627

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.

Upvotes: 10

rimero
rimero

Reputation: 2383

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 :

  • If your change is triggered by let's say a click event, you can get the selection and walk the tree from there.
  • Otherwise you'll need to walk the tree from the root

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

Upvotes: 2

Related Questions