Question

I'm new to JavaFx. I made my fxml file and I created my Controller. Everything works well for the moment. In my model, I have threads that download some files from the internet. And I want to notify the advancement to the UI (to update the progress indicator component).

How can I do it?

This is the Model method called by the Controller. I want to inform the user of the advancement of the process. For example : +10% every time a thread finishes.

 public void download(){
    ExecutorService pool = Executors.newSingleThreadExecutor();
    List<Future<String>> futures = new ArrayList<Future<String>>();
    futures.add(pool.submit(new Downloader(URL)));
    futures.add(pool.submit(new Downloader(URL)));
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    ... Manipulate downloaded files.
 }

How can I do it ? ^^

Was it helpful?

Solution

I suggest you to communicate with the controller, which will update the View. In this case, it would be a Supervising Controller, instead of the classic one.

A Supervising Controller has two primary responsibilities: input response and partial view/model synchronization. (Martin Fowler on Supervising Controller)

For that, I would create a callback interface on the model with an implementation on the controller. When calling download or constructing the model, or in a register method, I would pass the callback object from controller to model, and then the model would call update methods on it that would be treated in controller to update the GUI.

One important thing in your case is threading. As you're using JavaFX, if you do all of this in the main thread, your GUI will "freeze". So you must create another thread to donwnload your files.

Also, when in another thread, you won't be able to update the GUI. To do it correctly, you should use Platform.runLater(java.lang.Runnable runnable), so the Runnable passed will be executed on Main Thread by JavaFX.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top