我寫了一個方法,從KeyEvent的模擬按鍵,如下圖所示:模擬按鍵式的Java機器人
private Robot robot(){
if(robot==null){
try {
return new Robot();
} catch (AWTException e) {
throw new RuntimeException("Failed to create instance of Robot");
}
}else{
return robot;
}
}
public void sendKeyEvent(KeyEvent evt) throws IOException {
int type = evt.getID();
if(type == KeyEvent.KEY_PRESSED){
if(evt.isShiftDown()){
robot().keyPress(KeyEvent.VK_SHIFT);
}
robot().keyPress(evt.getKeyChar());
}else if(type == KeyEvent.KEY_RELEASED){
robot().keyRelease(evt.getKeyChar());
if(evt.isShiftDown()){
robot().keyRelease(KeyEvent.VK_SHIFT);
}
}
}
此方法時收到按「A」鍵時,它可以輸入「A」。
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='A',modifiers=Shift,extModifiers=Shift,keyLocation=KEY_LOCATION_UNKNOWN]]
但問題是,當它接收到該KeyEvent的(按 'A')時,它按下acturaly 「1」。
java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='a',keyLocation=KEY_LOCATION_UNKNOWN]]
有人能告訴我這種方法有什麼問題嗎?
爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2011-12-17 16:23:55
@AndrewThompson,謝謝你的建議。 – eric2323223 2011-12-17 16:34:54