我正在尝试将 JProgressBar 添加到我的程序中,但它不会更新!该值仅在其原因为 100% 时才会更改。这是我的方法。
public void downloadImages(List<String> images) {
if (errorCode == 0) {
for (int i = 0; i < images.size(); i++) {
if (errorCode == 0) {
main.progressLabel.setText("Downloading image " + Integer.toString(i + 1) + " of " + Integer.toString(images.size()));
String imageStr = images.get(i);
String imageName = imageStr.substring(imageStr.lastIndexOf("/") + 1);
try {
URL url = new URL(imageStr);
InputStream in = url.openStream();
OutputStream out = new FileOutputStream(saveDirectory + imageName);
byte[] b = new byte[2048];
int length;
while ((length = in.read(b)) != -1) {
out.write(b, 0, length);
}
in.close();
out.close();
} catch (MalformedURLException e) {
errorCode = BAD_URL;
} catch (IOException e) {
errorCode = INVALID_PATH;
}
main.progressBar.setValue(((i+1)/images.size())*100);
}
}
}
}
更改进度条值位于上述方法的底部。
这就是我如何称呼该方法。
public void download() {
final Downloader downloader = new Downloader(this, albumUrl.getText(), downloadPath.getText());
progressBar.setValue(0);
downloadButton.setEnabled(false);
new Thread(new Runnable() {
public void run() {
List<String> images = downloader.getImages(downloader.getPageSource());
downloader.downloadImages(images);
if (downloader.getErrorCode() == 0) {
progressLabel.setText("All images have been downloaded!");
} else {
String error = "";
switch (downloader.getErrorCode()) {
case Downloader.BAD_URL:
case Downloader.NOT_IMGUR_ALBUM:
error = "The URL entered is either invalid or does not link to an Imgur album.";
break;
case Downloader.BLANK_URL:
error = "The album URL field cannot be blank.";
break;
case Downloader.INVALID_PATH:
error = "The system cannot find the download directory path specified.";
break;
case Downloader.BLANK_PATH:
error = "The download directory cannot be blank.";
break;
case Downloader.CANNOT_READ_URL:
error = "An error occoured while reading the URL.";
break;
case Downloader.PARSING_ERROR:
error = "An error occoured while parsing the URL.";
break;
}
JOptionPane.showMessageDialog(Main.this, error, "Error", 0);
}
downloadButton.setEnabled(true);
}
}).start();
}
编辑:以上根本不是问题,问题之一是程序使用整数除法而不是十进制。