我想添加一個JProgressBar到我的程序,但它不會更新!一旦它導致100%,價值只會改變。這是我的方法。JProgressBar不會更新
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();
}
編輯:上面的問題根本不是問題之一,程序使用整數除法而不是小數。
+1我還在忙着輸入這個響應。現在的代碼Jonathan肯定會一直得到0。解決精度問題以及將用戶界面更新代碼從EDT移開應該使其正常工作。 –
+1 yup另一個問題OP有,也許是造成實際問題的一個問題,但在長時間運行的循環中更新Swing edt/on edt是不好的 –
我從來不知道java做到了這一點,對不起,但我從你們那裏學到了很多東西美國東部時間,所以謝謝:D –