微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用另一个线程时无法编辑 GUI

如何解决使用另一个线程时无法编辑 GUI

当我的一个方法调用时,它会创建一个新线程并开始下载文件。当该线程正在运行时,我的 GUI 中的 JLabel 应该更新下载完成的百分比。问题是我的 JLabel 直到下载完成后才会改变,即使我使用的是另一个线程。这是调用方法

public void downloadExe(String link,File path,JLabel message)
{
    this.link = link;
    this.path = path;
    Thread t1 = new Thread(this);
    t1.start();
    while (!percent.equals("100.00"))
        message.setText(percent);
}

还有run方法

public void run()
{
    try 
    {
        URL url = new URL(link);
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        double fileSize = (double)http.getContentLengthLong();
        BufferedInputStream in = new BufferedInputStream(http.getInputStream());
        FileOutputStream fos = new FileOutputStream(path);
        bufferedoutputstream bout = new bufferedoutputstream(fos,1024);
        byte[] buffer = new byte[1024];
        double downloaded = 0.00;
        int read = 0;
        double percentDownloaded = 0.00;
        while ((read = in.read(buffer,1024)) >= 0)
        {
            bout.write(buffer,read);
            downloaded += read;
            percentDownloaded = (downloaded*100)/fileSize;
            String percent = String.format("%.2f",percentDownloaded);
            codeFile(percent); // Passes local percent variable value into constructor which changes the value of the public variable,percent. 
        }
        bout.close();
        in.close();
    } catch (IOException e) {
        // Todo Auto-generated catch block
        e.printstacktrace();
    }
}

代码工作得很好,这意味着如果我打印到控制台而不是替换 JLabel,它会更新每个百分比。我曾尝试使用 JProgress 栏,因为它更适合下载,但在调用方法时它仍会冻结,直到下载完成。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。