0

我有一个带有自定义树节点的 JTree,我需要它在树注释标题被编辑后触发一个事件。到目前为止,我有这个:

tree.addTreeSelectionListener(new TreeSelectionListener() {
            public void valueChanged(TreeSelectionEvent e) {
                MyTreeNode node = (MyTreeNode) tree.getLastSelectedPathComponent();

                if (node == null) {
                    return;
                }
                //insert the new title in database
        });

但是,每次更改选择时都会触发。我需要在节点标题值发生更改时触发它,以便我可以在数据库中更新它。有什么帮助吗?

4

3 回答 3

2

a TreeSelectionListener listens, when the selection changes. 你想要的是一个EditListener,对吧?

那么您可以使用 getCellEditor 获取编辑器:http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/JTree.html#getCellEditor ( )

然后在 CellEditor 上添加一个侦听器: http ://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/CellEditor.html#addCellEditorListener(javax.swing.event.CellEditorListener )

于 2012-09-26T19:36:18.433 回答
2

我再次找到了解决方案。创建了一个自定义 TreeModelListener:

class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
    MyTreeNode node;
    node = (MyTreeNode)
             (e.getTreePath().getLastPathComponent());

    /*
     * If the event lists children, then the changed
     * node is the child of the node we have already
     * gotten.  Otherwise, the changed node and the
     * specified node are the same.
     */
    try {
        int index = e.getChildIndices()[0];
        node = (MyTreeNode)
               (node.getChildAt(index));
    } catch (NullPointerException exc) {}

    System.out.println("The user has finished editing the node.");
    System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
public void treeStructureChanged(TreeModelEvent e) {
}

}

并将其添加到树中:

DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
treeModel.addTreeModelListener(new MyTreeModelListener());

tree = new JTree(treeModel);
于 2012-09-26T20:03:27.527 回答
-1

将控制器(或具有控制流逻辑的另一个对象)注册到您的 MyTreeNode 对象。使用观察者模式并让控制器接收更改的实例。然后控制器可以将更改的值添加到 DB 中。

于 2012-09-26T19:30:34.497 回答