Link to home
Start Free TrialLog in
Avatar of shaharh
shaharh

asked on

JTree question (add/remove)

HI

I have a JTree component and I need to know :
1. how to delete a node from it
2. how to add a node and the new node will be editable when it added.

the foloowing code doesn't work:
to remove:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
node.getParent().remove(node);

to add:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
node.add(new DefaultMutableTreeNode("new node"));


thanks.
Avatar of shaharh
shaharh

ASKER

Edited text of question.
Did you update the GUI using
DefaultDataModel.notifyXXXXXX()
?
(going from mmeory here, might not be exactly right, but basically changeing the data is not enough, you have to tell the GUI that the data has changed too)
ASKER CERTIFIED SOLUTION
Avatar of msmolyak
msmolyak

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shaharh

ASKER

can you send me some code ?
I defined these two methods in the node class to add and remove children. Class RwAbstractTreeNode is the subclass of DefaultMutableTreeNode.

    /**
     * Add a child node to this node.
     */
    public void insertChildNode(RwAbstractTreeNode node)
    {
        DefaultTreeModel treeModel = (DefaultTreeModel) parentTree.getModel();
       
        node.setTree(getTree());

        treeModel.insertNodeInto(node, this, getChildCount());
    }

    /**
     * Remove a child node from this node.
     */
    public void removeChildNode(RwAbstractTreeNode node)
    {
        // Remove the child node from the tree
        DefaultTreeModel treeModel = (DefaultTreeModel) parentTree.getModel();

        treeModel.removeNodeFromParent(node);
    }