简体   繁体   中英

JProgressBar update not working

I have some code that moves files around and would like to implement a progress indicator while the files are being copied, but I'm having problems getting the progress bar to update - it just stays at 0. Here is the relevant code in question:

            public class SomeClass extends JFrame implements ActionListener
            {
                private static SomeClass myprogram = new SomeClass();
                private JProgressBar progressBar = new JProgressBar();

                public static void main(String[] args)
                {
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run()
                        {
                            myprogram.initGUI();
                        }
                    });
                }

                private void initGUI()
                {
                    JButton button1 = new JButton("Another Button");
                    JButton button2 = new JButton("Copy");
                    // other GUI Code
                }

                @Override
                public void actionPerformed(ActionEvent e)
                {       
                    JButton button = (JButton) e.getSource();
                    String text = button.getText();

                    if (text.equalsIgnoreCase("Copy"))
                    {           
                        copyFiles();
                    }
                    else
                    {           
                        doSomethingElse();
                    }
                }

                public void copyFiles()
                {       
                    for (int i = 0; i < someNumber; i++)
                    {
                        //Code to copy files
                        progressBar.setValue((i * 100) / someNumber);
                    }

                }
            }

Do I need to use SwingWorker to get this working properly? Thanks for any help.

To answer your question as to why your progress bar ain't updating:

Your JProgressBar ain't updating because you're blocking the Event Dispatch Thread (EDT) in your copyFiles() method.

You should never ever block the EDT with long-running operation.

What happens it that the actionPerformed callback is called from the EDT, so you're calling copyFiles() from the EDT too.

You should run the copyFiles from another thread.

Do I need to use SwingWorker to get this working properly?

SwingWorker would, indeed, be one way to run the copyFiles() code from outside the EDT.

I would use a ProgressMonitor . Here's a usage example.

您的答案是:

progressBar.update(progressBar.getGraphics());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM