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
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;
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With