自己的方法,抛砖引玉
问题:
javafx的UI线程中如果使用Thread.sleep(),会让整个UI卡死.
但是新建线程中sleep又会遇到This operation is permitted on the event thread only; currentThread = Thread-3,也就是不允许fx的对象在非ui线程上运行
方法:
通过Fx播放动画的方法模拟等待
用Timeline类循环,通过new PauseTransition(Duration.millis(100));在100ms后执行
代码:
//模拟按键z
Robot robot = new Robot();
//在100ms后执行抬起按键
PauseTransition pause = new PauseTransition(Duration.millis(100));
pause.setOnFinished(e -> robot.keyRelease(KeyCode.Z));
//Timeline每1秒循环执行按下按键
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), e2->{
robot.keyPress(KeyCode.Z);
pause.play();
}));
timeline.setCycleCount(Timeline.INDEFINITE);//无限循环
timeline.play();