Simple SWT File Drag'n'Drop example

In all fairness while I cannot blame SWT for my issues, with it being the non-standard Java GUI the documentation in this area is a lot thinner on the ground.  So a lot more trial and error with many of the techniques with SWT.  That is fine, one enjoys a challenge.  Once you get into the thinking of SWT things start falling into place.

What I wanted was for my SWT application to accept files dragged into it from external applications, namely file explorers etc.  I didn't want to support complex data; just give me the full path of the file that was dropped.  The code I eventually worked out is below:

DropTarget dt = new DropTarget(tableUpload, 
dt.setTransfer(new Transfer[] { FileTransfer.getInstance() });
dt.addDropListener(new DropTargetAdapter() {
public void drop(DropTargetEvent event) {
String fileList[] = null;
FileTransfer ft = FileTransfer.getInstance();
if (ft.isSupportedType(event.currentDataType)) {
fileList = (String[]);

The first thing we do is to create the DropTarget passing in the widget that we want to create the drop-zone for.  Here we use a previously created Table.  To accept files we only need to use the DROP_DEFAULT and DROP_MOVE flags.

We can use the FileTransfer class that handles all the data conversion for us giving us a String[] of full path names of all the files dropped.  Now so far all this was fairly obvious but where I became unstuck was what to do with the event that was passed in.

The key here is to first of all check that the data that was dropped is indeed something we can handle.  If someone drags some text to us for example, we don't want to handle that here.  So you make a call to the FileTransfer.isSupportedType() and if that returns true, then the event data is an array of String's, each one representing the full path of the file dropped.

Once I got that bit right, everything literally burst into life.


Recent Cloud posts

Recent JAVA posts

Latest CFML posts

Site Links