为什么我的Thread使我的JavaFX应用程序滞后? [英] Why is my Thread making my JavaFX Application lag?
问题描述
我正在尝试使用控制器类中的此代码创建一个跟踪鼠标移动的JavaFX应用程序:
I'm trying to make an JavaFX application that tracks the movement of my mouse for this im using this code in the controller class:
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();
但它使我的申请延迟了很长时间。
我该如何解决这个滞后问题?
But it couses my application to lag big time. How should i fix this lag problem?
谢谢我修好了:
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
What you doing is letting Javafx Application thread Thread.sleep(1000);
<-wait
你应该对JFX-AT进行任何长期行动。并且只更新你的ui组件。
Any long term action you shoud put OUT of JFX-AT. And only update your ui components on it.
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收到事件。
//Not sure if formatted and curly braces correctly.Bud you hopefully understand.Make sure you know which thread you let wait.Otherwise you wont be able to recieve events from paused jfxat.
这篇关于为什么我的Thread使我的JavaFX应用程序滞后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!