简体   繁体   English

如何使用 Java 将 text/html 和 text/plain 复制到剪贴板

[英]How to copy text/html and text/plain to clipboard using Java

I need to set clipboard contents, with a java application, such that there are two MIME types available to the user.我需要使用 java 应用程序设置剪贴板内容,以便用户可以使用两种 MIME 类型。 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 的例子,我希望有一个 Java 的等价物。

JavaScript Example: JavaScript 示例:

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:这基本上就是我在 Java 应用程序中所拥有的:

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.我知道如何使用“text/plain”字符串或“text/html”字符串设置内容。 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.上面的 Java 示例将在剪贴板中放置一个纯文本字符串,它可以很容易地修改为将 HTML 格式的文本放入剪贴板中 - 但只是其中之一,而不是两者。

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.如果我使用以下代码,我可以将剪贴板内容作为可转移的 object 获取,然后将剪贴板设置为相同的可转移的 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()"?例如,如果我可以创建自定义“Transferable”并将其放入“setContents()”?

Is there a way I can place both plain-text and HTML strings in the clipboard?有没有一种方法可以将纯文本和 HTML 字符串都放在剪贴板中?

So, after a little bit of playing around (and reading the updated JavaDocs).因此,经过一些尝试(并阅读更新后的 JavaDocs)。 The basic answer is.基本答案是。

  1. You need to supply both a "plain text" and "html text" value您需要同时提供“纯文本”和“html 文本”值
  2. You need to supply multiple data flavours, each representing the type of data you're willing to export您需要提供多种数据类型,每种类型代表您愿意导出的数据类型
  3. You need to return the appropriate data from getTransferData based on the flavour (and the flavours desired export method)您需要根据口味(以及所需的口味导出方法)从getTransferData返回适当的数据

Please Note请注意

This example exports two different strings, one is plain text and one is HTML, this is deliberate, so as it's easier to see when different text is used by different consumers.此示例导出两个不同的字符串,一个是纯文本,一个是 HTML,这是故意的,以便更容易看出不同的消费者使用不同的文本。 You could, obviously, use the html formatted text for both if you wished.显然,如果您愿意,可以对两者都使用 html 格式的文本。

在此处输入图像描述

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.ArrayList;
import java.util.List;

public final class Main {
    public static void main(String[] args) {

        String plainText = "Hello World";
        String htmlText = "<html><body><h1>This is a test</h1></body></html>";

        HtmlSelection htmlSelection = new HtmlSelection(htmlText, plainText);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(htmlSelection, null);
    }

    public static class HtmlSelection implements Transferable {

        private static List<DataFlavor> htmlFlavors = new ArrayList<>(3);

        static {
                htmlFlavors.add(DataFlavor.stringFlavor);
                htmlFlavors.add(DataFlavor.allHtmlFlavor);
        }

        private String html;
        private String plainText;

        public HtmlSelection(String html, String plainText) {
            this.html = html;
            this.plainText = plainText;
        }

        public DataFlavor[] getTransferDataFlavors() {
            return (DataFlavor[]) htmlFlavors.toArray(new DataFlavor[htmlFlavors.size()]);
        }

        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return htmlFlavors.contains(flavor);
        }

        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {

            String toBeExported = plainText;
            if (flavor == DataFlavor.stringFlavor) {
                toBeExported = plainText;
            } else if (flavor == DataFlavor.allHtmlFlavor) {
                toBeExported = html;
            }

            if (String.class.equals(flavor.getRepresentationClass())) {
                return toBeExported;
            }
            throw new UnsupportedFlavorException(flavor);
        }
    }
}

You should also beware that some applications may prefer a different method of export (ie via a Reader or InputStream ), this is demonstrated in...您还应该注意某些应用程序可能更喜欢不同的导出方法(即通过ReaderInputStream ),这在...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM