Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree make only leaves draggable

I need to make only leaves of a JTree draggable but the following code snippets makes every node in the tree draggable:

tree.setDragEnabled(true);

How can I restrict the draggable element to specific informationen of a tree node like the property myNode.isLeaf();

tia jaster

like image 491
jaster Avatar asked Jul 26 '11 09:07

jaster


1 Answers

This can be done by changing the TransferHandler of the JTree to return a null Transferable on non leaf nodes.

Here is a quick example:

    JTree tree = new JTree();
    tree.setDragEnabled(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    tree.setTransferHandler(new TransferHandler(null) {
        public int getSourceActions(JComponent c) {
            return MOVE;
        }

        protected Transferable createTransferable(JComponent c) {
            JTree tree = (JTree) c;
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent();

            if (node.isLeaf()) {
                // TODO create the Transferable instance for the selected leaf
            } else {
                return null;
            }
        }
    });
like image 153
Emmanuel Bourg Avatar answered Nov 16 '22 15:11

Emmanuel Bourg