<< 18 February 2009 | Home | 20 February 2009 >>

Drag'n'drop in SWT components

Those who went to my Lotusphere session already know this but doing drag'n'drop in SWT is actually quite easy. All you need to do is define a drag source and/or a drop target. The former is only required if a control in users should be able to drag data from a control in your code. The latter is required if you would like users to be able to drop stuff onto your component.

When setting up a drag source or a drop target you specify the control the source/target controls and the types of data you can provide/accept. These types are called Transfer types and are subclasses of the org.eclipse.ui.dnd.Transfer class.

Transfer types that might come handy - the class names should be pretty self-explanatory:

  • org.eclipse.swt.dnd.URLTransfer.getInstance()
  • org.eclipse.swt.dnd.FileTransfer.getInstance()
  • org.eclipse.swt.dnd.TextTransfer.getInstance()

Making a JFace viewer a drop target is simple passing in the underlying control:

DropTarget dropTarget = new DropTarget(viewer.getControl(), 
   DND.DROP_DEFAULT | DND.DROP_MOVE);

Once the drop target has been created you set the transfer types:

final Transfer[] dropTransferTypes = new Transfer[] {
  type1, 
  type2
};
dropTarget.setTransfer(dropTransferTypes);
The last thing you need is to add an instance of DropTargetListener or use a subclass of DropTargetAdapter as I do here:
dropTarget.addDropListener(new DropTargetAdapter() {
  ...
  ...
});

Creating a drag source is analogous.

Tags : , ,