Мне нужна помощь в моем Java проекте. Как динамически заполнить JTree из массивов String, заданных в виде путей? Например, 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"}};
Пример: Я пробовал приведенный ниже код, но он не объединяет похожие узлы. Это должны быть условия внутри метода 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);
}
}