How would I make a paste from java using the syste

2019-04-12 18:54发布

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

5条回答
家丑人穷心不美
2楼-- · 2019-04-12 19:13

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);
}
查看更多
可以哭但决不认输i
3楼-- · 2019-04-12 19:15

You could also try using the Clipboard class.

查看更多
Ridiculous、
4楼-- · 2019-04-12 19:21

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

}
查看更多
何必那么认真
5楼-- · 2019-04-12 19:21
贪生不怕死
6楼-- · 2019-04-12 19:39

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
查看更多
登录 后发表回答