Transferable: getTransferDataFlavors()
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.TransferHandler;
public class MainClass extends JFrame {
public MainClass() {
super("Drop Target");
JComponent cp = (JComponent) getContentPane();
cp.setTransferHandler(new MyFileTransferHandler()); // see below
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(150, 150);
}
public static void main(String[] args) {
new MainClass().setVisible(true);
}
}
class MyFileTransferHandler extends TransferHandler {
public boolean canImport(JComponent com, DataFlavor[] dataFlavors) {
for (int i = 0; i < dataFlavors.length; i++) {
DataFlavor flavor = dataFlavors[i];
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
System.out.println("canImport: JavaFileList FLAVOR: " + flavor);
return true;
}
if (flavor.equals(DataFlavor.stringFlavor)) {
System.out.println("canImport: String FLAVOR: " + flavor);
return true;
}
System.err.println("canImport: Rejected Flavor: " + flavor);
}
return false;
}
public boolean importData(JComponent comp, Transferable t) {
DataFlavor[] flavors = t.getTransferDataFlavors();
System.out.println("Trying to import:" + t);
for (int i = 0; i < flavors.length; i++) {
DataFlavor flavor = flavors[i];
try {
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
System.out.println("importData: FileListFlavor");
List l = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iter = l.iterator();
while (iter.hasNext()) {
File file = (File) iter.next();
System.out.println("GOT FILE: " + file.getCanonicalPath());
}
return true;
} else if (flavor.equals(DataFlavor.stringFlavor)) {
System.out.println("importData: String Flavor");
String fileOrURL = (String) t.getTransferData(flavor);
System.out.println("GOT STRING: " + fileOrURL);
try {
URL url = new URL(fileOrURL);
System.out.println("Valid URL: " + url.toString());
return true;
} catch (MalformedURLException ex) {
System.err.println("Not a valid URL");
return false;
}
} else {
System.out.println("importData rejected: " + flavor);
}
} catch (IOException ex) {
System.err.println("IOError getting data: " + ex);
} catch (UnsupportedFlavorException e) {
System.err.println("Unsupported Flavor: " + e);
}
}
return false;
}
}
Related examples in the same category