简体   繁体   English

Java swing,SwingWorker,进程栏不会更新

[英]Java swing, SwingWorker, process bar won't update

My swingworker won't repaint my progress bar(I have 2 classes). 我的摇摆工不会重绘进度条(我有2节课)。

This is my file downloader code. 这是我的文件下载器代码。 It puts percent of download in progress bar. 它会将进度百分比下载。

public class Downloader extends SwingWorker<String, Integer> {

 private String fileURL, destinationDirectory;
 private int fileTotalSize;

 public void DownloaderF(String file, String dir) {
    this.fileURL = file;
    this.destinationDirectory = dir;
 }

 @Override
 protected String doInBackground() throws Exception {
    try {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        String downloadedFileName = fileURL.substring(fileURL.lastIndexOf("/")+1);
        int filesize = httpConn.getContentLength();
        int responseCode = httpConn.getResponseCode();
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        int i = 0;
        int total = 0;
        BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
        FileOutputStream fos = new FileOutputStream(destinationDirectory + File.separator + downloadedFileName);
        BufferedOutputStream bout = new BufferedOutputStream(fos,4096);
        while ((i=in.read(buffer,0,4096))>=0) {
            total = total + i;
            bout.write(buffer,0,i);
            fileTotalSize = (total * 100) / filesize;
            publish(fileTotalSize);
        }
        bout.close();
        in.close();
    } catch(FileNotFoundException FNFE) {
        System.out.print("HTTP: 404!");
    } catch (IOException ex) {
        Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

 @Override
 protected void process(List<Integer> chunks) {
    try {
        Skin barValue = new Skin(); 
        barValue.setBar(fileTotalSize);
        //System.out.print("PROCESS:" + fileTotalSize + "\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
 }
}

This is my button code and progress bar value change method: 这是我的按钮代码和进度条值更改方法:

private void LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    // Дебаг
    Downloader downloadFile = new Downloader();
    downloadFile.DownloaderF("http://ipv4.download.thinkbroadband.com/100MB.zip", ".");
    downloadFile.execute();
}                                           

public void setBar(int Value) {
    DownloadBar.setValue(Value);
    DownloadBar.repaint();

    System.out.print("1\n");
}

"1\\n" will be printed, but progress bar won't move. “ 1 \\ n”将被打印,但是进度条不会移动。

Sorry for my bad english. 对不起,我的英语不好。

Most likely, your problem comes from this line: 您的问题很可能来自此行:

Skin barValue = new Skin();

You are recreating a new instance of you Skin class instead of referencing one that already exists. 您正在重新创建Skin类的新实例,而不是引用已经存在的实例。 Therefore, you most likely point to something that is probably not even displayed and hence you don't see anything happening. 因此,您最有可能指向的东西甚至可能没有显示,因此您什么也看不见。

The proper way to go is to provide to your class Downloader a reference to the original Skin containing your displayed "progress bar". 正确的做法是向您的类Downloader提供对包含所显示的“进度条”的原始Skin的引用。

FYI: 供参考:

  • No need to call repaint() on a JProgressBar when you change its value (the progress bar will do it for you) 更改其值时无需在JProgressBar上调用repaint()(进度条将为您完成此操作)
  • Please follow Java naming conventions (ie, method names and variables must start with a lower case letter): your code is a lot harder to read for experienced users. 请遵循Java命名约定(即方法名称和变量必须以小写字母开头):对于有经验的用户,您的代码很难阅读。

Here is a sample code derived from yours (although I made a few shortcuts) that actually works correctly as expected: 这是从您的代码中衍生的示例代码(尽管我做了一些快捷方式),它们实际上可以按预期正常工作:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class Skin {

    private JProgressBar DownloadBar;

    public static class Downloader extends SwingWorker<String, Integer> {

        private final String fileURL, destinationDirectory;
        private int fileTotalSize;
        private final Skin barValue;

        public Downloader(Skin skin, String file, String dir) {
            this.barValue = skin;
            this.fileURL = file;
            this.destinationDirectory = dir;
        }

        @Override
        protected String doInBackground() throws Exception {
            try {
                URL url = new URL(fileURL);
                HttpURLConnection httpConn = (HttpURLConnection) url
                        .openConnection();
                String downloadedFileName = fileURL.substring(fileURL
                        .lastIndexOf("/") + 1);
                int filesize = httpConn.getContentLength();
                int responseCode = httpConn.getResponseCode();
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                int i = 0;
                int total = 0;
                BufferedInputStream in = new BufferedInputStream(
                        httpConn.getInputStream());
                FileOutputStream fos = new FileOutputStream(
                        destinationDirectory + File.separator
                                + downloadedFileName);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 4096);
                while ((i = in.read(buffer, 0, 4096)) >= 0) {
                    total = total + i;
                    bout.write(buffer, 0, i);
                    fileTotalSize = total * 100 / filesize;
                    publish(fileTotalSize);
                }
                bout.close();
                in.close();
            } catch (FileNotFoundException FNFE) {
                System.out.print("HTTP: 404!");
            } catch (IOException ex) {
                Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE,
                        null, ex);
            }
            return null;
        }

        @Override
        protected void process(List<Integer> chunks) {
            barValue.setBar(fileTotalSize);
        }
    }

    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
        Downloader downloadFile = new Downloader(this,
                "http://ipv4.download.thinkbroadband.com/100MB.zip", ".");
        downloadFile.execute();
    }

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton login = new JButton("Login");
        login.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                loginButtonActionPerformed(e);
            }
        });
        DownloadBar = new JProgressBar();
        frame.add(login, BorderLayout.NORTH);
        frame.add(new JLabel(new ImageIcon(new URL(
                "http://home.scarlet.be/belperret/images/image1.jpg"))));
        frame.add(DownloadBar, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);
    }

    public void setBar(int Value) {
        DownloadBar.setValue(Value);
        DownloadBar.repaint();

        System.out.println("1");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new Skin().initUI();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

You are doing the publish(fileTotalSize) correctly, so I think it might be your process code. 您正在正确执行publish(fileTotalSize) ,所以我认为这可能是您的过程代码。 Try this change: 尝试此更改:

protected void process(List<Integer> chunks) {
   try {
       Skin barValue = new Skin(); 
       barValue.setBar( chunks.get(0) );
       //System.out.print("PROCESS:" + fileTotalSize + "\n");
   } catch (Exception ex) {
       ex.printStackTrace();
   }
}

I don't have your full code, so I can't test it out. 我没有您的完整代码,所以我无法对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM