Thread.sleep()は、現在のスレッド(キーを押し続けているスレッド)の実行を停止します。
一定の時間キーを押したままにしたい場合は、並列スレッドで実行する必要があります。ここで
は(あなたが他のコマンドを作成し、意志で内外にそれらを交換することができますので、コマンドパターンを使用しています)のThread.sleep()の問題を回避します提案です:
public class Main {
public static void main(String[] args) throws InterruptedException {
final RobotCommand pressAKeyCommand = new PressAKeyCommand();
Thread t = new Thread(new Runnable() {
public void run() {
pressAKeyCommand.execute();
}
});
t.start();
Thread.sleep(5000);
pressAKeyCommand.stop();
}
}
class PressAKeyCommand implements RobotCommand {
private volatile boolean isContinue = true;
public void execute() {
try {
Robot robot = new Robot();
while (isContinue) {
robot.keyPress(KeyEvent.VK_A);
}
robot.keyRelease(KeyEvent.VK_A);
} catch (AWTException ex) {
// Do something with Exception
}
}
public void stop() {
isContinue = false;
}
}
interface RobotCommand {
void execute();
void stop();
}
あなたはそうです。オンラインのjavaドキュメントを見ると、keyPressはキーを押すために使用され、keyReleaseは同じキーを解放するために使用されます。私は問題がthread.sleep()であると思う。 –