I need to set clipboard contents, with a java application, such that there are two MIME types available to the user. This will allow the user to paste the version of the text they want to.
I found an example that applies to JavaScript, I'm hoping that there is an equivalent for Java.
JavaScript Example:
const blob = new Blob([
'<a href="https://stackoverflow.com/">goto stack</a>'
], { type: "text/html" });
const blobPlain = new Blob(['goto stack'], { type: "text/plain" });
navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob,
[blobPlain.type]: blobPlain
},),
])
This is essentially what I have in my Java application:
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Clipboard;
public class tester{
public static void main(String[] args){
// from string to clipboard
StringSelection selection = new StringSelection("hi");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
}
I know how to set the contents, with either a "text/plain" string or a "text/html" string. The above Java example will place a plain-text string in the clipboard, it can easily be modified to put HTML formatted text in the clipboard instead - but only one or the other, not both.
If I use the following code, I can get the clipboard contents as a transferable object and then set the clipboard to that same transferable object.
@Override
public void run() {
try {
Transferable trans = systemClipboard.getContents(this);
setThisOwner(trans);
ClipboardMonitor.sleep(sleepInterval);
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
private void setThisOwner(Transferable clipContents) {
try {
systemClipboard.setContents(clipContents, this);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
The above isn't useful so far as my question here is concerned, but the code appears to indicate to me that there should be a way to do what I want to. If I could, for example, create a custom "Transferable" and place that in "setContents()"?
Is there a way I can place both plain-text and HTML strings in the clipboard?