使用Java将文本复制到剪贴板

问题

我想将文本从aJTable的单元格复制到剪贴板,使其可以粘贴到其他程序,如Microsoft Word。我有来自JTable的文字,但我不确定如何将其复制到剪贴板。


#1 热门回答(210 赞)

这适用于我,非常简单:

导入这些:

import java.awt.datatransfer.*;
import java.awt.Toolkit;

然后将这段代码放在你想要更改剪贴板的任何位置:

String myString = "This text will be copied into clipboard when running this code!";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);

我刚刚试过它并且有效。不确定代码中是否存在一些"最佳实践"缺陷,但它会解决你的问题!


#2 热门回答(10 赞)

以下类允许你将字符串复制/粘贴到剪贴板中。

import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import java.io.IOException;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();

        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        Clipboard systemClipboard = defaultToolkit.getSystemClipboard();

        return systemClipboard;
    }
}

#3 热门回答(4 赞)

这是以装饰方式书写的公认答案:

Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .setContents(
                new StringSelection(txtMySQLScript.getText()),
                null
        );