Skip to content

Commit d9447c6

Browse files
committed
Fix drag and drop of SwingFileWidget
On Windows, trying to get the TransferData during canImport() throws an InvalidDnDOperationException. Since we know the exception is coming, let's catch and ignore it. See: https://coderanch.com/t/664525/java/Invalid-Drag-Drop-Exception Thanks Stefan Helfrich for investigating.
1 parent c7d104e commit d9447c6

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/main/java/org/scijava/ui/swing/widget/SwingFileWidget.java

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
import java.awt.datatransfer.DataFlavor;
3434
import java.awt.datatransfer.UnsupportedFlavorException;
35+
import java.awt.dnd.InvalidDnDOperationException;
3536
import java.awt.event.ActionEvent;
3637
import java.awt.event.ActionListener;
3738
import java.io.File;
@@ -314,12 +315,34 @@ public FileTransferHandler(final String style) {
314315
@Override
315316
public boolean canImport(final TransferHandler.TransferSupport support) {
316317
if (!hasFiles(support)) return false;
317-
final List<File> allFiles = getFiles(support);
318-
if (allFiles == null || allFiles.size() != 1) return false;
319318

320-
final FileFilter filter = SwingFileWidget.createFileFilter(style);
321-
final List<File> files = SwingFileWidget.filterFiles(allFiles, filter);
322-
return files.size() == 1;
319+
// We wish to test the content of the transfer data and
320+
// determine if they are (a) files and (b) files we are
321+
// actually interested in processing. So we need to call
322+
// getTransferData() so that we can inspect the file names.
323+
// Unfortunately, this will not always work.
324+
// Under Windows, the Transferable instance
325+
// will have transfer data ONLY while the mouse button is
326+
// depressed. However, when the user releases the mouse
327+
// button, this method will be called one last time. And when
328+
// when this method attempts to getTransferData, Java will throw
329+
// an InvalidDnDOperationException. Since we know that the
330+
// exception is coming, we simply catch it and ignore it.
331+
// See:
332+
// https://coderanch.com/t/664525/java/Invalid-Drag-Drop-Exception
333+
try {
334+
final List<File> allFiles = getFiles(support);
335+
if (allFiles == null || allFiles.size() != 1)
336+
return false;
337+
338+
final FileFilter filter = SwingFileWidget
339+
.createFileFilter(style);
340+
final List<File> files = SwingFileWidget.filterFiles(allFiles,
341+
filter);
342+
return files.size() == 1;
343+
} catch (InvalidDnDOperationException exc) {
344+
return true;
345+
}
323346
}
324347

325348
@Override

0 commit comments

Comments
 (0)