java 设置剪贴板内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11596368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Clipboard Contents
提问by Nyx
I am trying to figure out why setting the contents of the system clipboard won't work for me. I programmatically set the clipboard contents. When i use the output part of the code, it works. However, when i try copy/pasting in any text editor, it is blank.
我想弄清楚为什么设置系统剪贴板的内容对我不起作用。我以编程方式设置剪贴板内容。当我使用代码的输出部分时,它可以工作。但是,当我尝试在任何文本编辑器中复制/粘贴时,它是空白的。
hovercraft edit, code from github:
气垫船编辑,来自github的代码:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws HeadlessException,
UnsupportedFlavorException, IOException {
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection("hi there"), null);
System.out.println(((String) Toolkit.getDefaultToolkit()
.getSystemClipboard().getData(DataFlavor.stringFlavor)));
}
}
回答by sexp1stol
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);
}
}
This program does it. It will set the String "hi" to clipboard. You can change it to a variable.
这个程序做到了。它将字符串“hi”设置为剪贴板。您可以将其更改为变量。
回答by user1277476
Linux cut and paste is a bit weird these days, because there are at least two different ways of doing it. In short, sometimes it's better to just paste with the middle button, and other times it's better to control-v, and sometimes neither seems to work.
现在 Linux 剪切和粘贴有点奇怪,因为至少有两种不同的方法可以做到。简而言之,有时用中间按钮粘贴更好,有时用 control-v 更好,有时似乎两者都不起作用。
Running autocutsel as a background process seems to help. http://www.nongnu.org/autocutsel/
将 autocutsel 作为后台进程运行似乎有帮助。 http://www.nongnu.org/autocutsel/