我正在使用从数据库填充的 JTree。
树是通过使用自定义对象设置根节点及其子节点来创建的:
private DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Categorias");
...
ResultSet primaryCategories = dbm.fetchAllCategories();
while (primaryCategories.next()){
Category category = new Category(primaryCategories.getLong("_id"),
primaryCategories.getString("category"));
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(category);
rootNode.add(childNode);
ResultSet currentSubcategory = dbm.fetchChildSubcategories(category.getCatId());
while (currentSubcategory.next()){
Category subcategory = new Category(currentSubcategory.getLong("_id"),
currentSubcategory.getString("category"));
childNode.add(new DefaultMutableTreeNode(subcategory, false));
}
}
...
在此之后,树就完美地创建了。填充有“类别”对象,每个对象都有自己的 ID 号和名称,以便在 toString() 方法中使用。
当它设置为可编辑时,问题就来了。重命名节点后,Category节点也会转换为String对象,因此我无法将新的 Category 名称值更新到数据库中。
我试图捕获重命名事件,treeNodesChanged(TreeModelEvent e)
但是,userObject 已经更改为字符串对象,并且无法获得编辑的对象的参考。
我有什么办法可以解决这个问题?每次发生更改时,我是否应该拥有显示的树的副本以及从数据库下载的另一个树并更新两者?
* PD: * 我还尝试从模型中捕获更改的节点,覆盖该方法:
public void nodeChanged(TreeNode newNode) {
DefaultMutableTreeNode parent = ((DefaultMutableTreeNode)newNode.getParent());
int index = getIndexOfChild(parent, newNode);
DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode) getChild(parent, index);
System.out.println(parent.getUserObject().getClass().toString());
System.out.println(oldNode.getUserObject().getClass().toString());
}
这打印:
class com.giorgi.commandserver.entity.Category
class java.lang.String
所以这里的旧节点已经更改为字符串,我已经完全丢失了对旧类别及其 ID 的引用,因此我无法在数据库中更新它。
欢迎任何帮助。