Ascalonian Ascalonian - 1 year ago 47
Java Question

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

I have a JTextField in my swing application that holds the file path of a file selected to be used. Currently I have a JFileChooser that is used to populate this value. However, I would like to add the ability for a user to drag-and-drop a file onto this JTextField and have it place the file path of that file into the JTextField instead of always having using the JFileChooser.

How can this be done?

Answer Source

First you should look into Swing DragDrop support. After that there are few little tricks for different operating systems. Once you've got things going you'll be handling the drop() callback. In this callback you'll want to check the DataFlavor of the Transferable.

For Windows you can just check the DataFlavor.isFlavorJavaFileListType() and then get your data like this

List<File> dropppedFiles = (List<File>)transferable.getTransferData(DataFlavor.javaFileListFlavor)

For Linux (and probably Solaris) the DataFlavor is a little trickier. You'll need to make your own DataFlavor and the Transferable type will be different

nixFileDataFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
String data = (String)transferable.getTransferData(nixFileDataFlavor);
for(StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();)
    String token = st.nextToken().trim();
    if(token.startsWith("#") || token.isEmpty())
         // comment line, by RFC 2483
         File file = new File(new URI(token))
         // store this somewhere
       // do something good