繁体   English   中英

可编辑的JTree将树节点转换为字符串

[英]A editable JTree converts the tree nodes into Strings

我正在使用从数据库填充的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 name值更新到数据库。

我尝试使用treeNodesChanged(TreeModelEvent e)捕获重命名事件,但是,userObject已经更改为String对象,并且无法获取编辑对象的参考。

我该怎样解决这个问题? 我是否应该拥有所显示的树的副本以及从数据库中下载的另一个树,并且每次发生更改时都要提升?

* 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

所以这里的旧节点已经改为String,我完全丢失了对旧类别及其ID的引用,所以我无法在数据库中更新它。

任何帮助都很好。

好的,这需要一些挖掘。

基本上,当编辑“停止”时, JTree将通过编辑器的getCellEditorValue请求编辑器的值。 然后通过valuesForPathChanged方法将其传递给模型,该方法最终调用节点的setUserObject方法。

据推测,您使用的是默认编辑器或基于文本字段的编辑器。 这将返回一个String值。

您需要做的是将更改捕获到树节点的setUserObject方法,访问即将到来的值(即,检查它是否为String )并根据需要进行更新。

正如MadProgrammer所说的最终解决方案是:

public void valueForPathChanged(TreePath path, Object newValue) {
        DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        Category catNode = (Category) aNode.getUserObject();
        catNode.setCategory((String) newValue);
        catNode.updateFromDatabase();
        nodeChanged(aNode);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM