用于显示java进度的线程

时间:2013-09-28 01:30:32

标签: java multithreading swing user-interface matisse

情况如下:我的代码从互联网上下载文件,同时显示其大小和文件名。

问题在于,当我下载该文件时,JTextArea中没有任何内容,并且框架就像“冻结”一样,直到下载完成。

我甚至尝试使用swingworker类放置一个进度条(我前几天要求提供信息,我不明白如何在我的代码中“整合”你之前给我的swingworker方法。我被告知使用Matisse在那种情况下根本不值得推荐。所以我不能使用swingworker。

我一直在研究,我认为适合我的方法是使用线程。有或没有进度条。只是寻找简单的代码,我是初学者,谢谢

3 个答案:

答案 0 :(得分:3)

这可能不是您当前问题的原因,但代码如下:

    } catch (MalformedURLException ex) {

    } catch (IOException ioe) { 

    }

等待发生的事故。如果发生任何异常,您已经告诉应用程序默默地忽略它们

就是不要这样做!

如果您对已检查的异常无法正确处理,则在方法签名中声明为thrown。不要把它扔掉。

答案 1 :(得分:0)

package org.assume.StackOverflow;

import java.io.File;

public class Progress implements Runnable
{
    private File file;
    private long totalSize;
    private int currentProgress;

    public Progress(String filePath, long totalSize)
    {
        this(new File(filePath), totalSize);
    }

    public Progress(File file, long totalSize)
    {
        this.file = file;
        this.totalSize = totalSize;
        new Thread(this).start();
    }

    public int getProgress()
    {
        return currentProgress;
    }

    @Override
    public void run()
    {
        while (file.length() < (totalSize - 100))
        {
            currentProgress = (int) (file.length() / totalSize);
        }
    }
}

如何使用它:

new Thread(new Progress(file, totalSize)).start();

答案 2 :(得分:0)

这些行实际上正在执行下载和编写

 while (b != -1) {
       b = in.read();
       if (b != -1) {
           out.write(b);
       }
 }

添加进度添加内容:

 while (b != -1) {
           b = in.read();
           if (b != -1) {
               downloaded += b;
               out.write(b);
           }
     }

进步是

downloaded / conn.getContentLength() * 100