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

房东的猫 提交于 2019-12-03 17:59:56

问题


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


回答1:


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



回答2:


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)
{

}



回答3:


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);
}



回答4:


You could also try using the Clipboard class.




回答5:


You have to use Java graphics library, eg. take a look at http://download.oracle.com/javase/1,5.0/docs/api/java/awt/datatransfer/Clipboard.html



来源:https://stackoverflow.com/questions/6631933/how-would-i-make-a-paste-from-java-using-the-system-clipboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!