Reputation: 418
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?
Thanks i fixed it:
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();
Upvotes: 0
Views: 1366
Reputation: 2841
What you doing is letting Javafx Application thread Thread.sleep(1000);
<-wait
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();
//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.
Upvotes: 2
Reputation: 2552
You call Thread.sleep(long)
inside a Runnable that will be executed on the UI thread. If the thread is sleeping, it can't do anything else but sleep there. If you want your label to update every 1000 milliseconds, you can use the java.util.Timer
class to make that happen.
Upvotes: 0
Reputation: 693
You should put your Thread.sleep()
call in your while loop and not in your Runnable
, otherwise the loop keeps posting a lot of runLater
tasks and those tasks stops the event thread for 1000ms after updating your mouse position
Upvotes: 0