0

I've a simple gui created with javaFx (java version 1.8.101) with a button and progress bar. I want to update the progress immediately after pressed the button. Inside the "event press button" I also have a simple for loop that prints a message for a number of times . The problem is that the progress bar is updated only at the end of print message loop and not at the same time independently from it. Here is the controller class

    package sample;

import com.sun.javafx.tk.Toolkit;
import javafx.beans.property.Property;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ProgressBar;

public class Controller {
    @FXML
    ProgressBar progressBar;


    @FXML
    private void handleStartBtnAction(ActionEvent event) throws InterruptedException {

        final int size = 100;
        Task<Integer> t = new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                int iterations;
                for (iterations = 0; iterations < size; iterations++) {
                    if (isCancelled()) {                        
                        break;
                    }                  
                    updateProgress(iterations, size);
                    System.out.println("update message " + iterations);
                    Thread.sleep(100);

                }
                return iterations;
            }
        };
        this.progressBar.progressProperty().bind((Property<Number>) t.progressProperty());
        Thread th = new Thread(t);
        th.setDaemon(true);
        th.start();

        for (int i = 0; i < 500000; i++) {
            System.out.println("print message " + i);

        }
    }

}
PoliC
  • 1
  • 1
  • 2
    The `for` loop at the end of the method is running on the FX Application Thread, so it will prevent the UI from updating (including re-rendering the progress bar) until it is complete. Presumably you are not really printing half a million messages to the console in the actual application: what is that for loop supposed to represent? If you have code there that takes a long time to run, you should execute it in a background thread. – James_D Apr 09 '18 at 14:38
  • Thank James, yes my loop simulated my real situation where I have a call to a method that preforms specific operations. The progress bar shall represent this, from the beginning to its completion – PoliC Apr 10 '18 at 08:05
  • You need to move that loop inside the `call()` method, in the task. – James_D Apr 10 '18 at 09:36

0 Answers0