Drop of one or more files in a Java Application

Matteo - 26 Apr 2005 02:26

This listener is very simple to use. Once created the window to make the drop on, for example identified by the object named myWnd, you can create the object MyDropTarget and associate it with the following code:

        dt.setComponent(myWnd);
        dt.setActive(true);

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.util.List;

class MyDropTarget extends DropTarget { MyDropTarget() { // some init... }

public void dragEnter(DropTargetDragEvent de) { if (de == null || !de.isDataFlavorSupported( DataFlavor.javaFileListFlavor)) { de.rejectDrag(); return; } de.acceptDrag(de.getDropAction()); } public void drop(DropTargetDropEvent de) { try { if (de == null || !de.isDataFlavorSupported( DataFlavor.javaFileListFlavor)) { de.rejectDrop(); return; } de.acceptDrop(de.getDropAction()); Transferable dt = de.getTransferable(); if (dt == null) { de.rejectDrop(); return; } List l = (List) dt.getTransferData( DataFlavor.javaFileListFlavor); de.getDropTargetContext().dropComplete(true); // do something with the file list...

} catch (Exception e) { e.printStackTrace(); de.rejectDrop(); } } }

 
Weblog Koan Projects Photos Contacts DW.net map