How to drop files from explorer into Java

All you need to do is call setDropTarget() on the component you need to drop onto, passing in a delegate object (in this case I created one called FileDropTarget) that handles the drop operation.

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
import java.util.List;

import javax.swing.JFrame;

public class Demo {
 public static void main(String[] args) {
  JFrame frame = new JFrame();
  frame.setDropTarget(new FileDropTarget());

 private static class FileDropTarget extends DropTarget {
  private static final long serialVersionUID = 1L;

  public synchronized void drop(DropTargetDropEvent event) {
   try {
    Transferable transferable = event.getTransferable();
    Object data = transferable.getTransferData(DataFlavor.javaFileListFlavor);
    List<File> list = (List<File>) data;
   } catch (Exception e) {
    // Non-file dropped

No comments:

Post a Comment