I am using this code in a Java Swing application to copy files to the clipboard:
final List<File> files = new ArrayList<File>();
// ... code to fill list omitted ... //
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
new Transferable() {
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.javaFileListFlavor };
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.javaFileListFlavor.equals(flavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return files;
}
}, null
);
It works, in that I can go to Windows Explorer and Ctrl+V and the files turn up (hopefully it works in other OSes, though not tested). I'd like to implement cut also but I don't know how to let the system know that that's what the action is, or alternatively, how to get feedback for each successfully copied file so I can delete it from its original location manually.
If this isn't impossible, any suggestions on how I should handle this? I'd like to be able to cut & paste within the application too (separately to exchanging files with the OS explorer).
The system clipboard can be accessed by calling Toolkit. getDefaultToolkit(). getSystemClipboard(). You can use this technique if you are interested in exchanging data between your application and other applications (Java or non-Java) running on the system.
A class that implements a mechanism to transfer data using cut/copy/paste operations. FlavorListener s may be registered on an instance of the Clipboard class to be notified about changes to the set of DataFlavor s available on this clipboard (see addFlavorListener(java. awt.
The setContents() method is used to set contents to Clipboard, like cut-copy operations, and the getContents() method is used to retrieve the content from Clipboard, like the paste operation. A data package to be set in the Clipboard must be wrapped in a Transferable object.
There is another post where people discuss the lack of a possibility to cut files:
Cutting files into the clipboard with SWT
If you really need it you could go the ugly way and check if there is a way to do this via JNI-calls, but then you have to do that for all platforms that you want to support...
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