Why is my JFrame blank while I do a download process?

徘徊边缘 提交于 2021-01-20 13:36:09

问题


I have a class that extends JFrame and inside it I have a method as follows:

public void downloadUrl(String filename, String urlString) throws MalformedURLException, IOException
{
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try
    {
        in = new BufferedInputStream(new URL(urlString).openStream());
        fout = new FileOutputStream(filename);

        byte data[] = new byte[1024];
        int count;
        int modPackSize = getModPackSize();
        while ((count = in.read(data, 0, 1024)) != -1)
        {
            fout.write(data, 0, count);
            downloadedPerc += (count*1.0/modPackSize)*100;
            progressBar.setValue((int) downloadedPerc);
            label.setText((int) downloadedPerc + "%");
            System.out.println(downloadedPerc);
        }

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {           
        if (in != null)
            in.close();
        if (fout != null)
            fout.flush();   
        fout.close();
    }
}

This method downloads the file and gets the downloaded percentage. While this is running, my JFrame is blank. After it runs, the JFrame updates and shows correctly, but I would want it to update(well, first show itself) often, how could I do that?


回答1:


You should use the SwingWorker class to implement the downloading task. Long-running tasks on the main thread freeze your GUI until the task is finished, this is why these tasks should be executed on a background thread. The SwingWorker class will allow you to do this and simultaneously update your progress bar.



来源:https://stackoverflow.com/questions/12347928/why-is-my-jframe-blank-while-i-do-a-download-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!