0

If I have the following situation:

package A;

public class class_A{
   private double progress = 0.0;
   public void run(){
      for (int i = 1; i <= 10; i++){
            try {
                this.progress += 0.1;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(i);
        }
   }
}

package B;

public class controller_B extends Controller{
   private ProgressBar pb;
   class_A a = new class_A();

   public void start_Run(ActionEvent event)
   {
      Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
               try {
                      a.run();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
               return null;
            }
        };
        Thread thread = new Thread(task);
        thread.start();
        progress_hdd.progressProperty().bind(task.progressProperty()); // this needs changing
   }
}

If I write the whole algorithm from run() into start_Run(), inside the new task and just bind the pb to the task, it works. However, I would like the algorithm to be in run() inside package A only, and in start_Run() I want to start the algorithm and bind the progress bar to the progress value from class_A. So far, I've tried multiple things, even using a getter for the progress in class_A, but the progress bar won't budge, unless I write everything inside the controller. Any ideas?

Andrei0408
  • 197
  • 7
  • As `updateProgress()` "is safe to be called from any thread," you may able to use the approach seen [here](https://stackoverflow.com/a/45718846/230513). – trashgod Apr 17 '22 at 15:33
  • With the setup you have this is not going to be possible; there is no way to access the `progress` field from outside `ClassA`. Simply adding a `getProgress()` method won’t work, because you would be forced to access the `progress` field from two different threads with no way to synchronize the access. Consider refactoring this as described in other comments. – James_D Apr 17 '22 at 17:41

0 Answers0