使用 Java 将文本复制到剪贴板
问题描述:
我想将文本从 JTable
的单元格复制到剪贴板,使其可以粘贴到 Microsoft Word 等其他程序中.我有来自 JTable
的文本,但我不确定如何将其复制到剪贴板.
I want to copy text from a JTable
's cell to the clipboard, making it available to be pasted into other programs such as Microsoft Word. I have the text from the JTable
, but I am unsure how to copy it to the clipboard.
答
这对我有用,而且很简单:
This works for me and is quite simple:
导入这些:
import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
然后将此代码片段放在您想要更改剪贴板的任何位置:
And then put this snippet of code wherever you'd like to alter the clipboard:
String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);