0

I'm having troubles using JProgressBar. I have a function that can take some time, and I want a progress bar on indeterminate mode while the function is being executed. I have a button that activates this function, and I've tried to setIndeterminate(true) before calling the function, and after that, setIndeterminate(false), but i don't get the progress bar moving at any time.

I have this code:

        progBar.setIndeterminate(true);
        //delay(12);
        //this.setEnabled(false);
        Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor();
        executor.execute(new Runnable() {@Override
            public void run() {
                    function1();

            }});

        //progBar.setIndeterminate(false);
        //progBar.setVisible(false);
        System.out.println("End Function");
        //-........................
    }

Also tried the function1() without any new executor. If I don't comment the line setIndeterminate(false), the progress bar doesn't start, but if I comment it, it always is on indeterminate mode.

Note that I'm using the Netbeans IDE to design some GUI, but coding most of the things myself (Only using NetBeans GUI for positioning).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Bertofer
  • 770
  • 6
  • 18
  • 1
    Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Implement a Swing `Timer` for repeating tasks or a **`SwingWorker`** for long running tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson May 27 '12 at 22:28

1 Answers1

1

You should probably move this code:

progBar.setIndeterminate(false);
progBar.setVisible(false);

into a SwingUtilities.invokeLater() block after calling function1().

The way it's set up now it will execute immediately after the setIndeterminate(true) call - that execute() method does not block.

For example:

executor.execute(new Runnable() {
        @Override
        public void run() {
                function1();
                // now fix the progress bar
                SwingUtilities.invokeLater(new Runnable() {
                    progBar.setIndeterminate(false);
                    progBar.setVisible(false);
                });
        }});
Rob I
  • 5,627
  • 2
  • 21
  • 28
  • Ok, it worked for me. Well, setIntermediate(false) is executed a little before the function ends, but not a problem. Thank you!! – Bertofer May 28 '12 at 09:01