Why is my Thread making my JavaFX Application lag?

旧城冷巷雨未停 提交于 2019-12-25 03:55:31

问题


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

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/24985985/why-is-my-thread-making-my-javafx-application-lag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!