Search code examples
javaswingiojprogressbarevent-dispatch-thread

Jprgressbar in Jdialog box not updating


i want to show the progress of copying the file from one folder to another using jprogressbar. All the thing i have done but jprogress bar run at the end and show 100% at the end. i am beginner and read topic in this form which says that i should use EDT, but still i didn't get all the thing. i also made another thread to update the Jprogress bar but nothing is happening. my part of code is

        jProgressBar1.setMinimum(0);
        jProgressBar1.setMaximum(100);
        try
        {
            fis = new FileInputStream(read);
            BufferedInputStream bins = new BufferedInputStream(fis);
            int b;
            long copied_data=0;
            for(int i =0;i<no_of_parts;i++)
            {
                copied_data = 0;
                fos = new FileOutputStream(jTextField2.getText()+"\\"+reading_file_name+".part"+i);
                bouts = new BufferedOutputStream(fos);
                while((b = bins.read())!= -1)
                {
                    bouts.write(b);
                    percentage = (progress*100)/file_size;
                    jProgressBar1.setValue(percentage);
                    copied_data++;
                    progress++;

                    if(copied_data==each_part_size_in_byte)
                    {
                        bouts.flush();
                        bouts.close();
                        break;
                    }
                }
                bouts.flush();
                bouts.close();

            }

        }catch(Exception e){}

Solution

  • The code that updates the progress bar should not be running on the same thread as the file copy operation. You need the file copy operation to run on a separate thread and a Swing timer to query the copy task for its progress and update the progress bar on the EDT periodically. You are currently performing everything on the EDT which prevents the progress bar from updating as you are locking up the event thread while the operation is in progress. You should only use the EDT for updating Swing components and everything else should be run in other threads.