我已经通过Robot类编写了一个打印字符串的函数。但是当我多次调用该函数时,每次它都打印最后一个字符串。以下是我的代码:
package test;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
public class ForTesting {
private static void typeInModalWindow(String stringToBeTyped) throws AWTException{
Robot robot = new Robot();
StringSelection stringSelection = new StringSelection(stringToBeTyped);
System.out.println("String recevied :: "+stringToBeTyped);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection,null);
clipboard.setContents(stringSelection,stringSelection);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
public static void main(String[] args) throws AWTException {
typeInModalWindow("USER");
typeInModalWindow("PASS");
typeInModalWindow("another");
//anotheranotheranother
}
}
为了说明这一点,在执行之前,我将光标停留在代码的最后一个注释部分中,因此结果被打印在那里。