我有一些URL在那裏的圖像。此圖像在每次請求期間都會更新(即每次請求(相同)URL都會返回一個新圖像)。假設這個URL指向CAPTCHA。 我的目標是在我的程序中加載並顯示幾個這樣的圖像。Java中的ImageIcon更新(來自互聯網)?
下面的代碼加載這些圖片到我的本地文件系統和工程確定(即,所有的圖像都不同,唯一的):
String filePath;
String urlPath;
int numOfFilesToDownload;
//Here filePath and urlPath are initialized.
//filePath points to the directory, where to save images
//urlPath is the url from where to download images
//numOfFilesToDownload is the number of files to download
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing connection
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Downloading image
try(InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(filePath + "img" + i + ".jpg")){
int b;
while((b = is.read()) != -1)
os.write(b);
}
}
但奇怪的事情發生了,當我嘗試以下的事情:
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
在後一種情況下,每個對話框包含相同圖像,即一個,第一個迭代期間下載。
此外,實驗表明,如果將「?r =」連接到urlPath(即簡單的GET請求參數),則url仍然有效。 而下面的代碼似乎是有效的,不正是它具有(即顯示的每個圖像是從以前不同):
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath + "?r=" + i);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
因此,我可以做一個結論,即ImageIcon的某種方式記住的網址中處理,根本不打擾兩次執行相同的工作...爲什麼和如何? javadoc中沒有關於它的東西。
您的代碼似乎並不尊重Swing線程規則。如果你爲此使用SwingWorker會發生什麼?考慮創建併發布[sscce](http://sscce.org)供我們測試。 – 2013-02-11 20:52:10