JProgressBar在下载期间不更新 [英] JProgressBar doesn't update during download

查看:320
本文介绍了JProgressBar在下载期间不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用swing按钮,我试图下载一个html文件,并将其写入一个新的html文件,同时做一个进度条。当我点击按钮,我的程序似乎冻结,直到下载完成,然后进度条突然100%。我不太确定如何解决这个问题,因为我是新的java。

Using a swing button, I'm trying to download an html file and write it to a new html file, while doing a progress bar. When I click the button, my program seems to freeze until the download finishes, and then the progress bar is suddenly 100%. I'm not quite sure how to fix this problem as I am new to java.

private void jButton2MouseReleased(java.awt.event.MouseEvent evt) {
    try {    
        URL oracle = new URL("http://mywebsite.com");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        String input_path = "d:/website/updatedsite.html";
        WriteFile data = new WriteFile(input_path, false);
        int length = yc.getContentLength();
        int current = 0;
        jProgressBar1.setMaximum(length);
        jProgressBar1.setValue(0);
        while ((inputLine = in.readLine()) != null) {
            data.writeToFile(inputLine);
            int i = 0;
            for (i = 0; i < length; i++) {
                jProgressBar1.setValue(i);
            }
        }
        in.close();
    }
    catch (java.io.IOException e) { 
    JOptionPane.showMessageDialog(Frame1.this, "Error " + e.getMessage());
}

}

推荐答案

这是因为你同时下载和更新进度条在同一个线程 - 这就是为什么gui下载完成后实际更新。

This is because you're both downloading and updating the progress bar in the same thread - that's why the gui gets actually updated AFTER the download is finished.

使用单独的工作线程进行下载,如此处,它应该工作。

Use a separate worker thread for downloading like explained here and it should work.

这篇关于JProgressBar在下载期间不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆