JProgressBar not working properly

前端 未结 2 996
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 09:18

So my JProgressBar I have set up doesn\'t work the way I want it. So whenever I run the program it just goes from 0 to 100 instantly. I tried using a Prog

2条回答
  •  余生分开走
    2020-12-22 09:30

    Swing is a single threaded environment, that is, there is a single thread which is responsible for processing all the events that occur within the system, including repaint events. Should anything block this thread for any reason, it will prevent Swing from processing any new events, including, repaint events...

    So all this ...

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);        }
            jProgressBar2.setValue(progress);
        }
    });
    

    Is constantly pausing the Event Dispatching Thread, preventing it from actually doing any updates (or at least spacing them randomly)...

    It's also likely that your outer loop is been run from within the context of the EDT, meaning that until it exists, nothing in the Event Queue will be processed. All your repaint requests will be consolidated down to a single paint request and voila, instant filled progress bar...

    You really should use a SwingWorker - I know you said you tried one, but you've not shown any code as to your attempt in this regards, so it's difficult to know why it didn't work, however...

    • SwingWorker and JProgressBar example
    • SwingWorker and JProgressBar example
    • SwingWorker and JProgressBar example
    • SwingWorker and JProgressBar example
    • SwingWorker and dual welding JProgressBar example
    • SwingWorker and JProgressBar example

    And forgive me if we haven't said this a few times before :P

提交回复
热议问题