How do you move nodes in a JTree?
I've got a JTree with a custom model which extends DefaultTreeModel. I need to be able to move a node from one branch to a different branch without losing the selection.
Currently, I'm doing it in my model like this:private void moveNode( MutableTreeNode开发者_StackOverflow中文版 node, MutableTreeNode newParent ) {
super.removeNodeFromParent( node );
super.insertNodeInto( node, newParent, 0 );
}
Since I'm using the DefaultTreeModel methods, the node gets to the right place and the tree view gets updated, but it also loses the selection on the node. That makes sense, since it's being (temporarily) removed but it's not the behavior I want.
What's the correct way to move a node like this? The selection after the move should be the same as before the move, whether that involves re-selecting the node after it's moved or not.
You have two options to choose from, the first being to roll your own subclass of JTree
that goes roughly 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; }
}
}
This way you always have the selection model at hand when needed and you can modify it in your move
method.
On the other hand similar functionality already exists in the drag and drop support, and the boilerplate to support DnD in considerable but managable (plus, you get, well, DnD support in your tree). The problem is that I do not know how to trigger a DnD event programmatically.
精彩评论