How can I use Drag-and-Drop in Swing to get file path?

In case you don’t want to spend too much time researching this relatively complex subject, and you’re on Java 7 or later, here’s a quick example of how to accept dropped files with a JTextArea as a drop target:

JTextArea myPanel = new JTextArea();
myPanel.setDropTarget(new DropTarget() {
    public synchronized void drop(DropTargetDropEvent evt) {
        try {
            evt.acceptDrop(DnDConstants.ACTION_COPY);
            List<File> droppedFiles = (List<File>)
                evt.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
            for (File file : droppedFiles) {
                // process files
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
});

Leave a Comment