Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the jtree node text runtime

Tags:

java

swing

jtree

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

like image 726
adesh singh Avatar asked Dec 15 '22 11:12

adesh singh


2 Answers

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.

like image 160
Guillaume Polet Avatar answered Jan 07 '23 10:01

Guillaume Polet


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

like image 38
rimero Avatar answered Jan 07 '23 12:01

rimero