0

I understand how to do indeterminate progress bars but I don't understand how to do determinate ones. For example say I'm using a JProgressBar to indicate I am loading a game. In loading this game I have information I want to load in information from some files and initialize variables:

private void load() {
    myInt = 5;
    myDouble = 1.2;
    //initialize other variables
}

And say I have 4 files I want to load information from. How do I translate this to give an accurate loading bar out of 100%?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Soggy_Toast
  • 57
  • 1
  • 9

1 Answers1

0

You need to do the work in a separate thread and update the progress bar's model as the work progresses.

It is important to perform the model updates in the Swing event thread, which can be accomplished by executing the update code with SwingUtilities.invokeLater.

For example:

public class Progress {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Loading...");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JProgressBar progressBar = new JProgressBar(0, 100);
        frame.add(progressBar);
        frame.pack();
        frame.setVisible(true);

        // A callback function that updates progress in the Swing event thread
        Consumer<Integer> progressCallback = percentComplete -> SwingUtilities.invokeLater(
            () -> progressBar.setValue(percentComplete)
        );

        // Do some work in another thread
        CompletableFuture.runAsync(() -> load(progressCallback));
    }

    // Example function that does some "work" and reports its progress to the caller
    private static void load(Consumer<Integer> progressCallback) {
        try {
            for (int i = 0; i <= 100; i++) {
                Thread.sleep(100);
                // Update the progress bar with the percentage completion
                progressCallback.accept(i);
            }
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
teppic
  • 7,051
  • 1
  • 29
  • 35
  • So does this mean I have to gauge the progress myself? Like for example, if I was loading 3 variables, does that mean each time I initialized a variable I would have to set the progress each time? Also, what does the `->` do? – Soggy_Toast Sep 12 '17 at 22:40
  • Yes, you'll have to update the progress bar yourself. See [this answer](https://stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java) re the arrow operator. – teppic Sep 12 '17 at 22:56