Riley Siebel
Riley Siebel

Reputation: 21

Letting User add Nodes to a JTree, nodes do not appear if parent has EVER been expanded

I have a problem with inserting nodes in a JTree. Basically the user right clicks on a parent node, bringing up a list of the possible children to insert. They select one it is inserted as a child of the selected node. This all works great when the parent node has never been expanded. However, if the parent node of the node the user is trying to insert has EVER been expanded, the UI doesn't seem to update accordingly.

Here are the relevant lines of code: Creating the JTree: this.tree = new JTree(ctlr.getRulesTableTreeModel().getModel()); The getModel() method returns a DefaultTreeModel models the original tree hierarchy.

Inserting a Node: this.treeModel.insertNodeInto(child, parent, index);

Sorry for not giving more code, but this project is like 3000 lines long, I'm trying to pick out the relevant lines.

Upvotes: 2

Views: 732

Answers (2)

pbvelikov
pbvelikov

Reputation: 53

After changing some node (adding child nodes to yourNode), you can call this:

((DefaultTreeModel)yourTree.getModel()).nodeStructureChanged((DefaultMutableTreeNode) yourNode);

I found this information here: https://coderanch.com/t/340158/java/Jtree-won-refresh-child-nodes

Upvotes: 0

Jill
Jill

Reputation: 539

You need to update the model.

Per the default tree model api:

http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultTreeModel.html

After you add a node, then you need to tell the model that the node was added; which will tell the ui to refresh properly.

For example:

nodesWereInserted(TreeNode node, int[] childIndices)
          

Invoke this method after you've inserted some TreeNodes into node.p

Upvotes: 2

Related Questions