How do you move nodes in JTree?

I have a JTree with a custom model that extends DefaultTreeModel. I need to move a node from one branch to another branch without losing selection.
I am currently doing this in my model as follows:

private void moveNode( MutableTreeNode node, MutableTreeNode newParent ) { super.removeNodeFromParent( node ); super.insertNodeInto( node, newParent, 0 ); } 

Since I use the DefaultTreeModel methods, the node gets to the right place, and the tree view is updated, but it also loses selection on the node. This makes sense as it is temporarily removed, but this is not the behavior I want.

What is the correct way to move a node as follows? The selection after the move should be the same as the one before the move, regardless of whether this involves re-selecting the node after moving it or not.

+4
source share
1 answer

You have two choices, the first of which is to flip your own JTree subclass, which looks something like this:

 public class MyTree extends JTree { public MyTree() { final MyTreeModel m = new MyTreeModel() super.setTreeModel(m); super.setSelectionModel(m.getSelectionModel()); } /** * your tree model implementation which fiddles * with sm when "move" is called */ private class MyTreeModel implements TreeModel() { private final DefaultTreeSelectionModel sm; public MyTreeModel() { this.sm = new DefaultTreeSelectionModel(); } public TreeSelectionModel getSelectionModel() { return this.sm; } } } 

Thus, you always have a selection model if necessary, and you can change it in your move method.

On the other hand, similar functionality already exists in drag and drop support and a template for supporting DnD in a significant but manageable way (plus, you get, well, DnD support in your tree). The problem is that I do not know how to programmatically fire the DnD event.

+4
source

All Articles