java 更改 jtree 节点文本运行时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16013097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:37:27  来源:igfitidea点击:

change the jtree node text runtime

javaswingjtree

提问by adesh singh

I am trying to create a JTree in java swing now i want to change the node text at runtime

我正在尝试在 java swing 中创建一个 JTree 现在我想在运行时更改节点文本

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

现在我想稍后我如何在子节点和大子节点中动态地和类似地将 A 1 更改为 2

回答by Guillaume Polet

You are looking for javax.swing.tree.DefaultMutableTreeNode.setUserObject(Object)

你正在寻找 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.

这假设您正在使用DefautltTreeModel.

回答by rimero

If you're not using a custom TreeModel, then the model of your tree is a DefaultTreeModel.

如果您没有使用自定义 TreeModel,那么您的树模型是DefaultTreeModel

You'll need to walk the tree with some kind of comparator, given your DefaultMutableTreeNodegetUserObject()(string or whatever) to achieve what you want.

考虑到您的 DefaultMutableTreeNode getUserObject()(字符串或其他),您需要使用某种比较器遍历树来实现您想要的。

You have 2 simpleoptions accordingly to your question and the code that you pasted :

根据您的问题和粘贴的代码,您有 2 个简单的选项:

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

成功更改后,您需要从模型中触发事件,这些事件将在稍后触发视图的重绘(nodesWereInserted等)。

Hope it helps

希望能帮助到你