gpt4 book ai didi

java - 为什么我的线程使我的 JavaFX 应用程序滞后?

转载 作者:行者123 更新时间:2023-12-02 05:35:50 24 4
gpt4 key购买 nike

我正在尝试创建一个 JavaFX 应用程序,在 Controller 类中使用以下代码来跟踪鼠标的移动:

 new Thread(new Runnable() {
@Override public void run() {
while (Main.running) {
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
label.setText(MouseInfo.getPointerInfo().getLocation().toString());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}

}).start();

但这导致我的应用程序严重滞后。我应该如何解决这个滞后问题?

谢谢我修复了它:

  new Thread(new Runnable() {
@Override public void run() {
while (Main.running) {

Platform.runLater(new Runnable() {
@Override
public void run() {
label.setText(MouseInfo.getPointerInfo().getLocation().toString());

}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}).start();

最佳答案

你所做的就是让Javafx应用程序线程Thread.sleep(1000); <-wait

您应该将任何长期行动排除在 JFX-AT 之外。并且只更新你的 ui 组件就可以了。

new Thread(()->{
while(Main.running){
Platform.runLater(()->{

//updateui component
//this is updating on FXAT

});
Thread.sleep(time)//This way you dont let JFXAT wait
}
}).start();

//不确定格式和花括号是否正确。希望您能理解。确保您知道让哪个线程等待。否则您将无法从暂停的 jfxat 接收事件。

关于java - 为什么我的线程使我的 JavaFX 应用程序滞后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com