2

I have the following piece of code:

@FXML public void initialize() {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            try {
                for(int i=0 ; i<10 ;i++) {
                    Thread.sleep(1000);
                    exampleButton.setText(String.valueOf(i));
                }
            }catch(Exception e) {}
        }
    });
}   

Which should obviously change the text of the button every second. According to this question, I put the sleep and the setText into a Platform.runLater-block, since GUI-modifications should not be done from the main thread. But my GUI is still freezing.

Why does this happen?

Moritz Schmidt
  • 2,635
  • 3
  • 27
  • 51
  • 4
    The loop is running on the "main event thread", preventing it from processing any new threads. This is kind of concurrency 101 - you should start by taking a look at [Concurrency in JavaFX](https://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm) – MadProgrammer Aug 13 '18 at 06:22
  • @MadProgrammer is totally right, use a `Task` or maybe a `Service` from `javafx.concurrent` package – deHaar Aug 13 '18 at 06:31
  • 1
    You could simply use a `Timeline` to do this. Of course, you need to make sure your controller class holds a strong reference of that `Timeline`. Also note that you do not need `@FXML` annotation if your `initialize()` method is `public`. – Jai Aug 13 '18 at 06:43

0 Answers0