JProgressBar没有进展

Kei*_*vis 1 java swing jprogressbar

所以我正在尝试使用进度条创建一个显示下载进度的下载程序.但我遇到问题,因为它实际上并没有更新进度条.基本上它保持白色,当它意味着蓝色.如果有人可以帮忙,代码如下.

JProgressBar progressBar = new JProgressBar(0, ia);
con.add(progressBar, BorderLayout.PAGE_START);
con.validate();
con.repaint();
progressBar = new JProgressBar(0, ia);
progressBar.setValue(0);
System.out.print("Downloading Files");
while ((count = in.read(data, 0, downloadSpeed)) != -1){
    fout.write(data, 0, count);
    if (count >= 2){
        progressBar.setString("Downloading : " + ia + " @ " + count + "Kbs per second");
    } else {
        progressBar.setString("Downloading : " + ia + " @ " + count + "Kb per second");
    }
    progressBar.setValue(count);
    con.add(progressBar, BorderLayout.PAGE_START);
    try{
        Thread.sleep(1000);
    } catch (Exception e){}
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 5

正如@happyburnout指出的那样,你最好在单独的线程中处理下载,使用SwingWorker可能是你正在做的最好的解决方案.

主要原因是您正在阻止事件调度线程(AKA EDT)运行,从而阻止处理任何重新绘制请求(以及其他UI重要事项).

你应该读一读

现在,这被认为是几乎直接从API文档,但给人的一个基本理念SwingWokerJProgressBar

工人"...

public class Worker extends SwingWorker<Object, Object> {

    @Override
    protected Object doInBackground() throws Exception {

        // The download code would go here...
        for (int index = 0; index < 1000; index++) {

            int progress = Math.round(((float)index / 1000f) * 100f);
            setProgress(progress);

            Thread.sleep(10);

        }

        // You could return the down load file if you wanted...
        return null;

    }
Run Code Online (Sandbox Code Playgroud)

"进度窗格"

public class ProgressPane extends JPanel {

    private JProgressBar progressBar;

    public ProgressPane() {

        setLayout(new GridBagLayout());
        progressBar = new JProgressBar();

        add(progressBar);

    }

    public void doWork() {

        Worker worker = new Worker();
        worker.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equals(evt.getPropertyName())) {
                    progressBar.setValue((Integer) evt.getNewValue());
                }
            }

        });

        worker.execute();

    }

}
Run Code Online (Sandbox Code Playgroud)

记住Swing的黄金法则

  • 从来没有,永远不会从ThreadEDT之外的任何其他组件更新UI组件
  • 始终在不同的任务上执行耗时的任务 Thread
  • (某些东西,某些东西,关于布局管理者 - 这更像是个人的东西;))

使用Swing,您将度过愉快而轻松的时光:D