JTree make only leaves draggable
Asked Answered
P

1

7

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

Pneumonoultramicroscopicsilicovolcanoconiosis answered 26/7, 2011 at 9:28 Comment(0)
V
6

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;
            }
        }
    });
Varner answered 26/7, 2011 at 11:38 Comment(1)
that's probably the only way, just a beware: all default dragging behaviour is lost when installing a custom handler. The sane thingy to do would be to delegate all operations to the default handler and only intercept the transferable creation, which unfortunately wasn't possible last time I looked (some important parts of BasicTransferHandler are package private or protected, forgot which exactly)Dope

© 2022 - 2024 — McMap. All rights reserved.