0

I have a JTree with custom tree nodes and I need it to fire an event after tree note title has been edited. So far I have this:

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

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

But, this fires everytime the selection is changed. I need it to fire when the node title value has changed so I can update it in the database. Any help?

Igor
  • 1,532
  • 4
  • 23
  • 44

3 Answers3

2

a TreeSelectionListener listens, when the selection changes. What you want is a EditListener, right?

then you can just get the editor with getCellEditor: http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/JTree.html#getCellEditor()

then add a Listener on the CellEditor: http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/CellEditor.html#addCellEditorListener(javax.swing.event.CellEditorListener)

Torsten
  • 96
  • 1
  • 6
2

Again I found a solution. Created a custom 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) {
}

}

And just added it to the tree:

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

tree = new JTree(treeModel);
Igor
  • 1,532
  • 4
  • 23
  • 44
-1

Register a controller (or another object with control flow logic) to your MyTreeNode objects. Use the observer pattern and let the controller receive the changed instance. Then the controller can add the changed values in the DB.

ollins
  • 1,851
  • 12
  • 16