Momo
Momo

Reputation: 3810

Removing children recursively from DefaultMutableTreeNode doesn't update in frame correctly

I have a JTree, projectView:

projectView = new JTree(projectViewTop);
projectView.setBackground(Color.WHITE);
projectView.setSize(250, getHeight());
projectView.setLocation(0, 0);
projectView.setVisible(true);
projectView.addKeyListener(this);
add(projectView);

Where projectViewTop is the main node (DefaultMutableTreeNode) of the JTree:

DefaultMutableTreeNode projectViewTop = new DefaultMutableTreeNode("Project");

The projectViewTop has a couple children nodes, which also contain sub-children as well (projectViewTop is the 'Project [My project]' node):

enter image description here

At one point, I need to clear every child of the projectViewTop node. I created this method to clear them recursively:

public void clearNode(DefaultMutableTreeNode node) {
    for (int i = 0; i < node.getChildCount(); i++) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
        clearNode(child);
    }
    node.removeAllChildren();
}

However, when I run this method, the content does not get cleared visually. This is what happens to the JTree display:

enter image description here

On the other hand, if I collapse the main node, it clears everything properly (it seems the visuals only get updated when I collapse the main node). How can I prevent 'dirt' children nodes staying on the main node when clearing it?

Upvotes: 0

Views: 604

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

You need to notify the TreeModel that the structure has changed.

For whatever reason (I'm assuming it's an optimisation choice), the nodes have no (direct) connection to the TreeModel, they are kind of like two models working together, but where one isn't talking to the other ... yes, this is very annoying

So when you modify the "node" tree, you need to notify the TreeModel and will cause an update to the JTree ...

DefaultTreeModel has a nodesWereRemoved method which you can use, if you're using a DefaultTreeModel.

Upvotes: 1

Related Questions