2010-12-09 20 views
2

我有一個包com.supercorp.killerapp並在它是一個包(com.supercorp.killerapp.views)如果我不創建與guiformbuilder應用:你在哪裏把你正在加載的圖像按鈕在Java應用程序?

  • 如何設置的圖標在視圖目錄中的JInternalFrame上的按鈕的位置?
  • 一般來說,如何訪問不同文件夾中的圖像?
  • 我的所有圖像是否應包含在一個單獨的文件夾中?

我使用的語法是:

JButton iconButton = new JButton(new ImageIcon("page_delete.png")); 

按鈕不顯示圖像。

回答

4

我把它包含我的應用程序,在一個名爲com.example.GreatApp.resources,然後包裝使用加載它的jar:

getClassLoader().getResourceAsStream(
       "com/example/GreatApp/resource/icon.png");` 

更新。完整的例子

/** 
* Creates and returns an ImageIcon from the resource in jar. 
* @param location resource location in the jar, 
* like 'com/example/GreatApp/res/icon.png' or null if it was not found. 
*/ 
public ImageIcon createImageIconFromResource(String location) 
      throws java.io.IOException { 
    java.io.InputStream input = getClassLoader().getResourceAsStream(
       location); 
    // or throw an ioexception here aka `file not found` 
    if(input == null) return null; 
    return new ImageIcon(ImageIO.read(input)); 
} 
3

您可以將圖像放在類路徑的任何位置。我覺得把它們放在項目的根目錄下的「圖像」文件夾是最合理的。

軟件包編譯時映射到文件夾&包裝的,所以它看起來像你需要:

Image im = Toolkit.getDefaultToolkit().getImage("/com/supercorp/killerapp/views/page_delete.png"); 
JButton iconButton = new JButton(new ImageIcon(im)); 
+1

這是否工作或做你需要做的`新的ImageIcon(的getClass()。的getResource( 「/ COM/...」))`?我不認爲`ImageIcon(String)`構造函數從類路徑加載。 – 2010-12-09 17:04:48

+1

哎呀,你是對的 – javamonkey79 2010-12-09 17:09:46

相關問題