0
我有一个数据库(代码,composant,父)的表,其中每个节点都有一个父(父也是一个组件代码),我需要从选择动态填充一个treeView从数据库动态填充javaFX treeView
编译没事的时候@FXML
private TreeView tree;//declaration of the treeView
HashMap<Integer, composant> node = new HashMap<>(); //for child nodes
HashMap<Integer, composant> pere = new HashMap<>(); //for parent nodes
composant c; //object from component class
private void fillTree(String idSys) {
String query = "SELECT * FROM composant WHERE id=?";
try {
ps = cnx.prepareStatement(query);
ps.setString(1, idSys);
rs = ps.executeQuery();
while (rs.next()) {
int code = rs.getInt("code");
String composant = rs.getString("composant");
int parent = rs.getInt("parent");
String niveau = rs.getString("niveau");
int id = rs.getInt("id");
c = new composant(code, composant, niveau, parent, id);
node.put(code, c);
pere.put(parent, c);
}
ps.close();
rs.close();
} catch (Exception e) {
System.err.println("Error" + e);
}
TreeItem<String> system = new TreeItem<>(sys);
//brows and fill parents node
for (Integer k : pere.keySet()) {
composant p = pere.get(k);
TreeItem<String> parent = new TreeItem<>();
parent.setValue(p.getComposant());
//brows and fill child hashmap
for (Integer i : node.keySet()) {
composant c = node.get(i);
TreeItem<String> noeud = new TreeItem<>();
noeud.setValue(c.getComposant());
if (c.getParent() == k) {
//if the parent = 1 it must attach to the root node
if (k == 1) {
system.getChildren().add(noeud);
} else {
parent.getChildren().add(noeud);
}
}
}
}
tree.setRoot(system);
}
我不确定构建树结构的算法是否正确,但如果在GUI中出现* nothing *,则表明您没有发布任何错误。 (至少你应该看到你的根节点。)我建议你尝试创建一个[MCVE];代替访问数据库,硬编码一些'composant'实例并将它们放入地图中。你应该可以在很少的代码行中做到这一点。如果这不起作用,那么你可以在你的问题中发布完整的例子;如果确实如此,您将能够缩小问题所在。 –