在javafx线程中模拟sleep等待而不卡死UI或报错This operation is permitted on the event thread only; currentThread的方案

本文介绍了在JavaFX的UI线程中避免Thread.sleep导致卡死的问题,通过创建Timeline和PauseTransition来实现100ms的模拟按键延迟,确保在非UI线程操作被允许的情况下保持界面响应。
摘要由CSDN通过智能技术生成

自己的方法,抛砖引玉

问题:

        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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值