我正在创建一个编辑器应用程序,并且我的菜单有问题。在"对象"菜单中,我想使用JTree
显示几种对象类型。这些对象类型是通过插件动态注册的,并遵循以下样式:
trigger.button
trigger.lever
out.door.fallgate
trigger.plate
out.door.door
...
此名称列表是未分类的,我想为JTree
构建TreeNode
结构:
- 触发
- 按钮
- 杠杆
- 板块
- 淘汰
- 门
- Fallgate
- 门
- 门
此外,如果用户选择叶节点,我需要从 TreePath
重新创建对象名称(例如trigger.button)。有人可以建议如何做到这一点。
在psuedocode中,这是您需要做的...
public TreeNode buildTree(){
String[] names = new String[]; // fill this with the names of your plugins
TreeNode tree;
// for each plugin name...
for (int i=0;i<names.length;i++){
String currentName = names[i];
String[] splitName = currentName.split(".");
// loop over the split name and see if the nodes exist in the tree. If not, create them
TreeNode parent = tree;
for (int n=0;n<splitName.length;n++){
if (parent.hasChild(splitName[n])){
// the parent node exists, so it doesn't need to be created. Store the node as 'parent' to use in the next loop run
parent = parent.getChild(splitName[n]);
}
else {
// the node doesn't exist, so create it. Then set it as 'parent' for use by the next loop run
TreeNode child = new TreeNode(splitName[n]);
parent.addChild(child);
parent = child;
}
}
return tree;
}
这只是psoudocode-您需要做正确实施treenode方法的工作,等等。自己做,那么我们将更愿意帮助您解决小问题。
-
请参阅Oracle Jtree教程
-
部分动态更改树,检查代码示例
-
similair Idea