2016-03-31 101 views
0

我創建了一個擴展ImageIcon的自定義類,以便傳遞文件url和給定的顏色,它加載重繪它的圖像。 這個類包裝在一個.jar文件中,我用它來開發不同的用戶界面(我們稱之爲UI.jar)。從資源或不同的文件夾加載圖像

這個類應該被設想爲加載位於UI.jar包裝的文件夾中的圖像,其他圖像打包在另一個.jar文件中,其他圖像與其他URL一起,可能位於未包裝在.jar中的文件夾中。所以我開發了這個代碼:

BufferedImage bi = null; 
try{ 
    //CASE 1: the image related to this url is packed in a .jar file 
    bi = ImageIO.read(resourceClass.getResource(url)); 
}catch(Exception e){ 
    try{ 
     //CASE 2: the image related to this url is somewhere else 
     bi = ImageIO.read(new File(url)); 
    }catch(Exception ee){ 
     //CASE 3: none of the above 
     ee.printStackTrace(); 
    } 
} 

此方法,但問題是,我一直通過resourceClass爲延伸ImageIcon的我的自定義類的參數,這是一個有點棘手,不舒服。

還有其他方法可以實現我的目標嗎?

+0

小性能/代碼問題:不需要外部的'try/catch'。相反,你可以測試'Class.getResource(url)'是否返回'null'。 – haraldK

回答

1

我在這裏看到的三個備選

  1. 的getClass()。的getResource(字符串)
  2. ImplementationClassName.class.getResource(字符串)
  3. Reflection.getCallerClass()的getResource(字符串)

任何這些應該做的工作。

當你不喜歡前三個,你可以嘗試這個,但這更醜陋。

StackTraceElement[] se = Thread.currentThread().getStackTrace(); 
//se[0] = Thread.getStackTrace() 
//se[1] = your method 
//se[2] = your callers method 
Class x = Class.forName(se[2].getClassName()); 
x.getResource(url); 
+0

也'getClass()。getClassLoader()' –

+0

這個問題是'getClass()'方法總是返回它調用的類,在我的情況下,這個類打包在'UI.jar'中。因此,如果我作爲參數傳遞的url引用位於另一個目錄中的文件或者打包在另一個jar文件中(其中'UI.jar是該jar的依賴項),該方法不起作用。在這種情況下, – Roberto

+0

Reflection.getCallerClass是你的。 – tejoe

相關問題