简体   繁体   English

如何在JTree中移动节点?

[英]How do you move nodes in a JTree?

I've got a JTree with a custom model which extends DefaultTreeModel. 我有一个带有自定义模型的JTree,它扩展了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 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. 由于我正在使用DefaultTreeModel方法,因此节点到达正确的位置并且树视图会更新,但它也会丢失节点上的选择。 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: 你有两个选择可供选择,第一个是滚动你自己的JTree子类,大致如下:

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. 这样,您可以在需要时随时拥有选择模型,您可以在move方法中对其进行修改。

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). 另一方面,拖放支持中已经存在类似的功能,并且支持DnD的样板很多但是可以管理(另外,你得到了,树中的DnD支持)。 The problem is that I do not know how to trigger a DnD event programmatically. 问题是我不知道如何以编程方式触发DnD事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM