拖动时禁用TreeNode选择

时间:2016-07-20 14:13:55

标签: java swing drag-and-drop jtree mouselistener

我有一个Jtree和一个自定义MouseListener / MouseMotionListener来处理Touch设备上的滚动。

我的问题是,当我开始拖动时,当我按下鼠标时,当前节点将立即被选中。

问题: 如何在拖动鼠标时禁用自动选择(当我点击它而不拖动时应该选择它。)

我的DragscrollListener中的clickedpressed函数为空。

注意:

我还没有对DragScrollListener进行编码 - 可以找到它here

示例代码:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;

public class Test extends JFrame{

    public Test(){

        JTree tree = new JTree();

        JScrollPane pane = new JScrollPane(tree);

        DragScrollListener ds = new DragScrollListener(tree);
        tree.addMouseListener(ds);
        tree.addMouseMotionListener(ds);

        getContentPane().add(pane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        this.setSize(100,100);

    }

    public static void main(String[]arghs){
        new Test();
    }
}

1 个答案:

答案 0 :(得分:2)

要在拖动完成时控制所需的行为,请覆盖释放的鼠标 DragScrollListener通过扩展它。请参阅注释以获得澄清:

public class Test extends JFrame{

    public Test(){

        JTree tree = new JTree();

        JScrollPane pane = new JScrollPane(tree);

        //To control the needed behavior when drag is finished, override 
        //mouse released in DragScrollListener by extending it
        MyDragScrollListener ds = new MyDragScrollListener(tree);

        tree.addMouseListener(ds);
        tree.addMouseMotionListener(ds);

        getContentPane().add(pane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        this.setSize(100,100);
    }

    //Subclass DragScrollListener to override mouse released 
    public class MyDragScrollListener extends DragScrollListener{

        public MyDragScrollListener(Component c) {
            super(c);
        }

        @Override
        public void mouseReleased(MouseEvent e){

            //add needed functionality when mouse is released 
            if( e.getSource() instanceof JTree) {

                System.out.println("source is a JTree");
                JTree tree = (JTree)e.getSource();

                //clear seelction
                 tree.clearSelection(); 

            }

            super.mouseReleased(e);
        }
    }

    public static void main(String[]arghs){
        new Test();
    }
}

不要犹豫,询问代码是否不够清晰。