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?
(Note that the process is the same when dragging from a native application to a Java application.) In a nutshell, the drag and drop process works like this: Rollo has selected a row of text in the source component: the list. While holding the mouse button Rollo begins to drag the text — this initiates the drag gesture.
HTML Drag and Drop interfaces enable web applications to drag and drop files on a web page. This document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page.
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 continue; } try { File file = new File(new URI(token)) // store this somewhere } catch(...) { // do something good .... } }
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(); } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With