Search code examples
javajavafxprogress-bar

I want to loop through a list and want to show a progressBar while looping through that list


i have two different classes into two different files One class is for ProgressBar

public class ProgressBarController implements Initializable {

    @FXML
    public ProgressBar progressBar;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}

and another class is where i want to loop through the list and want to update the progress on the basis of that list

public class AnotherClass {
    public Envelope function(List<Invoice> invoiceList) throws IOException {
        for(Invoice invoiceModel : invoiceList) {
            // update the progressBar and do some work


        }
    }
}

I tried to create a new thread

Task<Void> task = new Task<>() {
     @Override
     public Void call() {
        for (int i = 0; i < 100; i++) {
           // do some work
           updateProgress(i + 1, 100);
           try {
          Thread.sleep(200);
       } catch (InterruptedException e) {
          e.printStackTrace();
       }
        }
        return null;
     }
};
progressBar.progressProperty().bind(task.progressProperty());
Thread thread = new Thread(task);
thread.start();

but this was not working either my progress bar is not updating and if it is then it is updating after complete all other task.

I want to update the progressBar on the basis of data in for loop.


Solution

  • Here is an example that shows how to update the ProgressBar for a list of Tasks. My guess is that What I have in the Button is similar to what you should have in for(Invoice invoiceModel : invoiceList).

    Key Code

    task.setOnSucceeded((event) -> {
        System.out.println("finished working on url " + t.toString());                    
        bar.setProgress(((float)counter.incrementAndGet()) / urlsList.size());
        System.out.println("Counter: " + counter    + "\t list size: " + urlsList.size());
    });
    

    Full Code

    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.atomic.AtomicInteger;
    import javafx.application.Application;
    import javafx.concurrent.Task;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ProgressBar;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    
    /**
     * Creates a FlowPane and adds some rectangles inside. A LayoutAnimator is set
     * to observe the contents of the FlowPane for layout changes.
     */
    public class App extends Application {
    
        private final ExecutorService exec = Executors.newSingleThreadExecutor(r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        });
        
        AtomicInteger counter = new AtomicInteger(0);
        
        @Override
        public void start(Stage primaryStage) {
            List<URL> urlsList = getURLs();
    
            ProgressBar bar = new ProgressBar(0);
            
            Button btnProcessUrls = new Button("Process URLs");
            btnProcessUrls.setOnAction((onAction) -> {
                List<Task> taskList = new ArrayList();
    
                urlsList.forEach((t) -> {
                    Task task = new Task<Void>() {
                        @Override
                        public Void call() {
                            System.out.println("I starting working on URL " + t.toString());
                            //Simulate long running task
                            for (int i = 0; i < 1000000000 ;i++) {
                                //System.out.print("working on url " + t.toString() + "\r");
                            }
                            return null;
                        }
                    };
    
                    task.setOnSucceeded((event) -> {
                        System.out.println("finished working on url " + t.toString());                    
                        bar.setProgress(((float)counter.incrementAndGet()) / urlsList.size());
                        System.out.println("Counter: " + counter    + "\t list size: " + urlsList.size());
                    });
                    
                    taskList.add(task);
                });
                
                taskList.forEach(exec::submit);
            });
    
            VBox root = new VBox(bar, btnProcessUrls);
            Scene scene = new Scene(root, 300, 250);
    
            primaryStage.setTitle("Flow Layout Test");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public List<URL> getURLs() {
            List<URL> urls = new ArrayList();
            simulateQueringDbForUrlStrings().forEach((t) -> {
                try {
                    urls.add(new URL(t));
                } catch (MalformedURLException ex) {
                    System.out.println(ex.toString());
                }
            });
    
            return urls;
        }
    
        public List<String> simulateQueringDbForUrlStrings() {
            String dbResults = """
                               http://www.youtube.com
                               http://www.facebook.com
                               http://www.baidu.com
                               http://www.yahoo.com
                               http://www.amazon.com
                               http://www.wikipedia.org
                               http://www.qq.com
                               http://www.google.co.in
                               http://www.twitter.com
                               http://www.live.com
                               http://www.taobao.com
                               http://www.bing.com
                               http://www.instagram.com
                               http://www.weibo.com
                               http://www.sina.com.cn
                               http://www.linkedin.com
                               http://www.yahoo.co.jp
                               http://www.msn.com
                               http://www.vk.com
                               http://www.google.de
                               http://www.yandex.ru
                               http://www.hao123.com
                               http://www.google.co.uk
                               http://www.reddit.com
                               http://www.ebay.com
                               http://www.google.fr
                               http://www.t.co
                               http://www.tmall.com
                               http://www.google.com.br
                               http://www.360.cn
                               http://www.sohu.com
                               http://www.amazon.co.jp
                               http://www.pinterest.com
                               http://www.netflix.com
                               http://www.google.it
                               http://www.google.ru
                               http://www.microsoft.com
                               http://www.google.es
                               http://www.wordpress.com
                               http://www.gmw.cn
                               http://www.tumblr.com
                               http://www.paypal.com
                               http://www.blogspot.com
                               http://www.imgur.com
                               http://www.stackoverflow.com
                               http://www.aliexpress.com
                               http://www.naver.com
                               http://www.ok.ru
                               http://www.apple.com
                               http://www.github.com
                               http://www.chinadaily.com.cn
                               http://www.imdb.com
                               http://www.google.co.kr
                               http://www.fc2.com
                               http://www.jd.com
                               http://www.blogger.com
                               http://www.163.com
                               http://www.google.ca
                               http://www.whatsapp.com
                               http://www.amazon.in
                               http://www.office.com
                               http://www.tianya.cn
                               http://www.google.co.id
                               http://www.youku.com
                               http://www.rakuten.co.jp
                               http://www.craigslist.org
                               http://www.amazon.de
                               http://www.nicovideo.jp
                               http://www.google.pl
                               http://www.soso.com
                               http://www.bilibili.com
                               http://www.dropbox.com
                               http://www.xinhuanet.com
                               http://www.outbrain.com
                               http://www.pixnet.net
                               http://www.alibaba.com
                               http://www.alipay.com
                               http://www.microsoftonline.com
                               http://www.booking.com
                               http://www.googleusercontent.com
                               http://www.google.com.au
                               http://www.popads.net
                               http://www.cntv.cn
                               http://www.zhihu.com
                               http://www.amazon.co.uk
                               http://www.diply.com
                               http://www.coccoc.com
                               http://www.cnn.com
                               http://www.bbc.co.uk
                               http://www.twitch.tv
                               http://www.wikia.com
                               http://www.google.co.th
                               http://www.go.com
                               http://www.google.com.ph
                               http://www.doubleclick.net
                               http://www.onet.pl
                               http://www.googleadservices.com
                               http://www.accuweather.com
                               http://www.googleweblight.com
                               http://www.answers.yahoo.com
                               http://www.youtube.com
                               http://www.facebook.com
                               http://www.baidu.com
                               http://www.yahoo.com
                               http://www.amazon.com
                               http://www.wikipedia.org
                               http://www.qq.com
                               http://www.google.co.in
                               http://www.twitter.com
                               http://www.live.com
                               http://www.taobao.com
                               http://www.bing.com
                               http://www.instagram.com
                               http://www.weibo.com
                               http://www.sina.com.cn
                               http://www.linkedin.com
                               http://www.yahoo.co.jp
                               http://www.msn.com
                               http://www.vk.com
                               http://www.google.de
                               http://www.yandex.ru
                               http://www.hao123.com
                               http://www.google.co.uk
                               http://www.reddit.com
                               http://www.ebay.com
                               http://www.google.fr
                               http://www.t.co
                               http://www.tmall.com
                               http://www.google.com.br
                               http://www.360.cn
                               http://www.sohu.com
                               http://www.amazon.co.jp
                               http://www.pinterest.com
                               http://www.netflix.com
                               http://www.google.it
                               http://www.google.ru
                               http://www.microsoft.com
                               http://www.google.es
                               http://www.wordpress.com
                               http://www.gmw.cn
                               http://www.tumblr.com
                               http://www.paypal.com
                               http://www.blogspot.com
                               http://www.imgur.com
                               http://www.stackoverflow.com
                               http://www.aliexpress.com
                               http://www.naver.com
                               http://www.ok.ru
                               http://www.apple.com
                               http://www.github.com
                               http://www.chinadaily.com.cn
                               http://www.imdb.com
                               http://www.google.co.kr
                               http://www.fc2.com
                               http://www.jd.com
                               http://www.blogger.com
                               http://www.163.com
                               http://www.google.ca
                               """;
    
            String[] urls = dbResults.split("\n");
    
            List<String> urlsStringList = new ArrayList();
            for (String url : urls) {
                urlsStringList.add(url.strip());
            }
    
            return urlsStringList;
        }
    }
    

    Output

    enter image description here