我在抓住如何使用数据库中的数据填充SWING JTREE时遇到了一些麻烦。说我的数据看起来像这样:
id | parent_fk | folder |
1 | NULL | Customer
2 | NULL | Accounts
3 | NULL | Templates
4 | 1 | TestCustomer
6 | 4 | TestAlbum1
8 | 4 | TestAlbum2
我打算做的是填充一个JFrame JTree(比如info_tree),root是root,有一个孩子“TestCustomer”,这个孩子有两个孩子是“TestAlbum1”和“TestAlbum2”
我所做的是:
现在我似乎陷入困境,如何循环让孩子通过parent_fk链接到正确的父母
public void TreeExample() {
Connection conn = null;
try {
//<editor-fold defaultstate="collapsed" desc="connection">
String CS = "******";
String user = "*****";
String password = "*****";
conn = (Connection) DriverManager.getConnection(CS, user, password);
String prepSqlStatement = "Select * FROM ag_album";
PreparedStatement stat = conn.prepareStatement(prepSqlStatement);
ResultSet rs = stat.executeQuery();
ArrayList id = new ArrayList();
List folder = new ArrayList();
ArrayList parent_fk = new ArrayList();
// create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultTreeModel treeModel = new DefaultTreeModel(root);
while (rs.next()) {
id.add(rs.getString("id"));
parent_fk.add(rs.getString("parent_fk"));
folder.add(rs.getString("folder"));
}
int i = 0;
for (Object r : id) {
// create the child nodes
DefaultMutableTreeNode idNode = new DefaultMutableTreeNode(folder.get(i));
root.add(idNode);
i++;
}
info_tree.setModel(treeModel);
} catch (Exception e) {
Logger.getLogger(BrandITFrame.class.getName()).log(Level.SEVERE, null, e);
}
}
我尝试了一个查看parent_pk中对象的foreach循环,但这导致树没有显示出来。例如:
int j = 0;
for (Object f : parent_fk) {
idNode.add(new DefaultMutableTreeNode(folder.get(j)));
j++;
}
我似乎停留在逻辑上,找出如何从我的resultSet中获取项目,将它们作为子项添加到也来自同一resultSet的父项。
如果有人可以提供帮助,请提前感谢您!