我将如何使用系统剪贴板从 Java 粘贴?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6631933/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:43:06  来源:igfitidea点击:

How would I make a paste from java using the system clipboard?

javaclipboard

提问by Globmont

I want to make a paste from the system clipboard in java. How would I do this?

我想在java中从系统剪贴板粘贴。我该怎么做?

回答by user85116

While the robot class would work, it's not as elegant as using the system clipboard directly, like this:

虽然机器人类可以工作,但它不如直接使用系统剪贴板那么优雅,如下所示:

private void onPaste(){
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable t = c.getContents(this);
    if (t == null)
        return;
    try {
        jtxtfield.setText((String) t.getTransferData(DataFlavor.stringFlavor));
    } catch (Exception e){
        e.printStackTrace();
    }//try
}//onPaste

回答by The Java Man

You could use the robot class like this

你可以像这样使用机器人类

try
{
    Robot r = new Robot();
    r.keyPress(KeyEvent.VK_CONTROL);
    r.keyPress(KeyEvent.VK_V);
    r.keyRelease(KeyEvent.VK_CONTROL);
    r.keyRelease(KeyEvent.VK_V);

}
catch(Exception e)
{

}

回答by Mr_Hmp

Try this

试试这个

public static void type(String characters) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection stringSelection = new StringSelection( characters );
clipboard.setContents(stringSelection, instance);
//control+V is for pasting...
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}

回答by The Java Man

You could also try using the Clipboard class.

您也可以尝试使用 Clipboard 类。

回答by Murali VP