Thursday, 7 April 2011

Java Drag and Drop Summary

Key concepts


The core class in Java Drag and Drop (DnD) is the TransferHandler. This can be used to transfer data to and from both Java and native applications in the same way.


  • All JComponents support DnD automatically. Use the setDragEnabled to enable the default behaviour for the component.
  • DnD to and from any JComponent can be customised by calling setTransferHandler with your own TransferHandler.
  • To provide the effect of being able to drop something anywhere on the application, assign a suitable TransferHandler to all components from the JPanel downwards.
  • Assigning a TransferHandler overrides the default behaviour. Careful consideration should be made if there are complex requirements.

TransferHandler Drag Methods


When sub-classing a TransferHandler, the following are the methods to override to control the drag source behaviour.


  • getSourceActions Controls which drag types are supported from this component.
  • createTransferrable When a drag is started, the data to send is bundled up into a Transferable which will be delivered to the drop target.
  • exportDone Signalled when a drag has been completed using this TransferHandler.

TransferHandler Drop Methods


The drop methods below control the behaviour of a component which is to be the drop target for a DnD operation.


  • canImport Called repeatedly to determine whether the component to receive the drop is able to.
  • startImport Called when the drop is initiated.

No comments:

Post a Comment