JTree'节点标题编辑'听众

时间:2012-09-26 18:00:37

标签: java listener jtree

我有一个带有自定义树节点的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
        });

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

3 个答案:

答案 0 :(得分:2)

当选择更改时,TreeSelectionListener将侦听。你想要的是一个EditListener,对吗?

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

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

答案 1 :(得分: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);

答案 2 :(得分:-1)

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