JProgressBar not working properly

前端 未结 2 991
佛祖请我去吃肉
佛祖请我去吃肉 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:43

    You are evoking Thread.sleep inside the EvokeLater which means that it is running on another thread than your for loop. i.e., your for loop is completing instantaneously (well, however long it takes to loop from 1 to 100, which is almost instantaneously).

    Move Thread.sleep outside of EvokeLater and it should work as you intend.

        int max = 10;
        for (int i = 0; i <= max; i++) {
            final int progress = (int)Math.round(
                100.0 * ((double)i / (double)max)
            );
    
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    jProgressBar2.setValue(progress);
                }
            });
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(BandListGenerator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    

    Edit: agree with @MadProgrammer. It appears this is just an illustrative question, but you should make sure whatever you're trying to accomplish here you use a SwingWorker for.

提交回复
热议问题