Search code examples
javaprogressmonitor

Progress Monitor:Progress interval


As shown in below code, I have 4 functions in it and I manually set each of the progress interval of the progress monitor = 25%.

But my approach will more be impractical to set the progress interval manually if I have like 20 or more functions.

what will be a better approach to set the progress interval given X number of functions?

class Task extends SwingWorker<Void, Void> {
    @Override
    public Void doInBackground() {
        int progress = 0;
        setProgress(0);
        while (progress < 100 && !isCancelled()) 
        {   
            functionA();
            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex) {
                ex.printStackTrace();
            }
            progress += 25;
            setProgress(Math.min(progress, 100));

            taskOutput.setText("Step 2");
            functionB();
            progress += 25;
            setProgress(Math.min(progress, 100));

            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex) {
                ex.printStackTrace();
            }

            taskOutput.setText("Step 3");
            functionC();
            progress += 25;
            setProgress(Math.min(progress, 100));

            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex) {
                ex.printStackTrace();
            }

            taskOutput.setText("Step 4");
            functionD();
            try {
                Thread.sleep(1000);
            }catch(InterruptedException ex) {
                ex.printStackTrace();
            }
            progress += 25;
            setProgress(Math.min(progress, 100));
        }
        return null;
    }

Solution

  • int numberOfFunctions = 20;
    int progress = 0;
    ...
    function1();
    setProgress((++progress * 100) / numberOfFunctions);  // progress is 5%
    ...
    function20();
    setProgress((++progress * 100) / numberOfFunctions);  // progress is 100%