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.io.File;
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());
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

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

  @Override
  @SuppressWarnings("unchecked")
  public synchronized void drop(DropTargetDropEvent event) {
   try {
    event.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
    Transferable transferable = event.getTransferable();
    Object data = transferable.getTransferData(DataFlavor.javaFileListFlavor);
    List<File> list = (List<File>) data;
    System.out.println(list.get(0).getAbsolutePath());
   } catch (Exception e) {
    // Non-file dropped
   }
  }
 }
}

No comments:

Post a Comment