开发者

Renaming the JTree Node Manually in Java

I have created a jtree with the root node "RootNode" and some other n开发者_开发百科odes like "Node1","Node2", Node3".

After creation of tree I want to rename the rootnode or any other node by manually. We can rename the node dynamically by using the method

 jtee.setEditable(true);

But I want to change the name in manualy by the code level

like

 someMethod(Arg1 oldNodeName,Arg2 newNodeName)

Is there any way to do this?


Assuming you are using a DefaultMutableTreeNode you could just change the UserObject (whose toString() method is what is used to display the node name) by calling: setUserObject() on the node you want to change.


I'll assume you're using a tree with a DefaultTreeModel, using instances of DefaultMutableTreeNode.

You'll have to iterate through the tree nodes and find the one which has the oldNodeName as user object, then change its user object to newNodeName, and call the method nodeChanged of the tree model.


To properly rename a DefaultMutableTreeNode, you must set it's new user object as well as notify the JTrees table model the node changed so it can resize it for the shorter/longer text.

Assuming your tree is using a DefaultTreeModel, use this:

public void renameNode(JTree tree, DefaultMutableTreeNode node, Object new_user_object) {
     node.setUserObject(new_user_object);
     ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
}


It does change the UI, if:

  • you are using a DefaultTreeModel model
  • you actually change the UserObject

This is to say something like this:

// TheNode is a CustomMutableTreeNode (extending DefaultMutableTreeNode)
// and points to the selected node to alter
String NewNodeName = Dlg.NewNodeName.getText();
if(!NewNodeName.isEmpty()) {
    ON.setName(NewNodeName); // ON is the real source data
    TheNode.setUserObject(NewNodeName);
    ((DefaultTreeModel)JSONTree.getModel()).nodeChanged(TheNode);
}

It took me quite a while to figure out that changing the source data (in ON) did nothing on the UI, even with a repaint();. You really have to update theUserObject (a String from the DefaultMutableTreeNode)

Once this done, it's the easiest and most elegant solution IMO.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜