Search code examples
javajavafxwindowprogressindicator

JavaFX progress indicator in a new window won't "spin"


I made login screen and now I must do some background work that takes about 8-10seconds and I made new window with the progress indicator (indeterminate) but it just pop's out and it's static (not spinning), I assume I'm doing something wrong with the thread part, here is the code :

Task<Boolean> loginTask = new Task<Boolean>() {
        @Override
        protected Boolean call() throws Exception {
            return true;
        }
    };

    loginTask.setOnRunning(e -> {

           //background task(collecting data)

    });

And after this I did this :

 Thread thread = new Thread(loginTask);
    thread.setDaemon(true);
    thread.start();

    //progress indicator window
    Parent p = null;
    try {
        p = FXMLLoader.load(getClass().getResource("/fxml/loginLoader.fxml"));
        p.setVisible(true);
        Scene scene = new Scene(p);
        Stage wndw = new Stage();
        this.loadingStage=wndw;
        wndw.setTitle("Loading data... Please wait.");
        wndw.setScene(scene);
        wndw.show();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

And it pop's out but it's static :

enter image description here

What I need to do to make progress indicator to spin?


Solution

  • You're monopolizing the JavaFX Application Thread which means it can't update the UI, thus the ProgressIndicator does not animate.

    Task<Boolean> loginTask = new Task<Boolean>() {
        @Override
        protected Boolean call() throws Exception {
            return true;
        }
    };
    
    loginTask.setOnRunning(e -> {
        //background task(collecting data)
    });
    

    Your comment suggests you're doing the actual work in the onRunning handler which is not the correct way to use a Task. That handler is invoked on the FX thread when the Task enters the RUNNING state; it's meant as a callback where you can, for example, update the UI to indicate the change in status. The actual work of the task should be done in the call() method which is invoked on the background thread.