Java剪贴板复制和粘贴

时间:2017-05-15 10:35:42

标签: java awtrobot

Java Robot库的行为不稳定,有时我能够从剪贴板中复制代码,但有时它只是粘贴空白。我做错了吗?

String getClipboardData(){
    Robot robot;
    String clipData=null;
    try {
        robot = new Robot();
        robot.keyPress(KeyEvent.VK_ALT);
        robot.keyPress(KeyEvent.VK_E);
        robot.keyRelease(KeyEvent.VK_E);
        robot.keyPress(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_C);
        robot.keyRelease(KeyEvent.VK_ALT);
        try {
            Thread.sleep(500);                 //1000 milliseconds is one second.
        }catch(InterruptedException ex) {
           Thread.currentThread().interrupt();
        }
        Clipboard c=Toolkit.getDefaultToolkit().getSystemClipboard();
        // Get data stored in the clipboard that is in the form of a string (text)

        try {
             clipData = (String) c.getData(DataFlavor.stringFlavor);
             //System.out.println(clipData);
         } catch (UnsupportedFlavorException | IOException e) {
             e.printStackTrace();
         }
    }catch (AWTException e1) {                                   
         e1.printStackTrace();
    }
    return clipData;
}              

0 个答案:

没有答案