繁体   English   中英

JProgressBar更新不起作用

[英]JProgressBar update not working

我有一些代码可以移动文件,并希望在复制文件时实现进度指示器,但是我在更新进度条时遇到问题-它始终保持为0。这是相关的代码:

            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);
                    }

                }
            }

我需要使用SwingWorker使其正常工作吗? 谢谢你的帮助。

要回答有关进度栏为什么不更新的问题,请执行以下操作:

您的JProgressBar无法更新,因为您要在copyFiles()方法中阻止事件调度线程 (EDT)。

您永远不要通过长时间运行来阻止EDT。

从EDT调用actionPerformed回调会发生什么,因此您也从EDT调用copyFiles()

您应该从另一个线程运行copyFiles

我需要使用SwingWorker使其正常工作吗?

实际上,SwingWorker将是从EDT外部运行copyFiles()代码的一种方法。

我将使用ProgressMonitor 这是一个用法示例。

您的答案是:

progressBar.update(progressBar.getGraphics());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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