【发布时间】:2020-06-29 10:35:58
【问题描述】:
我的 Java 项目需要帮助。如何从模式化为路径的字符串数组动态填充我的 JTree? 比如,字符串
paths[][]={{"Animals", "Birds","Non_flying" ,"Chicken"},
{"Animals","Birds","Non_flying","Ostrich"},
{"Animals","Birds","Flying","Eagle"},
{"Animals","Birds","Flying","Crow"},
{"Animals","Reptiles","Lizard"},
{"Plants"," Fruit Bearing","Fruits","Mango"},
{"Plants"," Fruit Bearing","Vegetable","Eggplant"},
{"Plants"," Non-fruit Bearing","Sunflower"}};
Like this 我尝试了下面的代码,但它没有合并相似的节点。一定是treeify()方法里面的条件:
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeTest extends javax.swing.JFrame{
static JTree tree;
public static void setTree(){
String paths[][]={{"Animals", "Birds","Non_flying" ,"Chicken"},
{"Animals","Birds","Non_flying","Ostrich"},
{"Animals","Birds","Flying","Eagle"},
{"Animals","Birds","Flying","Crow"},
{"Animals","Reptiles","Lizard"},
{"Plants"," Fruit Bearing","Fruits","Mango"},
{"Plants"," Fruit Bearing","Vegetable","Eggplant"},
{"Plants"," Non-fruit Bearing","Sunflower"}};
tree = new JTree(treeify(paths));
}
public static <T> DefaultMutableTreeNode treeify(String[][] paths) {
DefaultMutableTreeNode root = null;
DefaultMutableTreeNode subRoot = null;
for ( String[] parent : paths)
for ( String value : parent){
if (root == null) {
root = new DefaultMutableTreeNode(value);
} else if (subRoot == null){
subRoot = new DefaultMutableTreeNode(value);
root.add(subRoot);
} else {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(value);
subRoot.add(child);
subRoot = child;
}
}
return root;
}
public static void main(String[] args) {
TreeTest test = new TreeTest();
setTree();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.add(new JScrollPane(tree));
test.setSize(500,400);
test.setLocationRelativeTo(null);
test.setVisible(true);
}
}
【问题讨论】:
-
您必须搜索您正在构建的模型才能知道新节点适合的位置。假设您正在尝试添加
{"Animals", "Birds","Non_flying" ,"Chicken"}。从根作为您的“当前”节点开始,并寻找一个名为"Animals"的子节点;如果你没有找到它,添加一个空的"Animals"节点作为“当前”的子节点。现在,将找到或添加的"Animals"节点设为您的新“当前”节点,并在 其 子节点中查找"Birds"节点,必要时添加它,依此类推... -
任何可以在这里给我代码的人。我是 JTree 的新手。花了 2 周时间解决问题,但没有任何效果。