2012-06-04 166 views
0

我正在使用NetBeans GUIBuilder創建一個JPanel窗體。我添加了一個JLabel,並使用NetBeans的界面爲其提供來自外部圖像的圖標(.png)。路徑經過驗證,圖像顯示在GUIBuilder屏幕上。它甚至出現在我點擊「預覽設計」按鈕時。運行項目時不顯示。 GUI的其餘部分顯示爲應該顯示。你們有沒有人知道爲什麼會發生這種情況和/或如何解決這個問題?Netbeans ImageIcon不顯示

很多人一直在尋求SSCCE。由於代碼是由NetBeans Form Builder生成的,因此我還包括了用來製作JLabel的步驟。重點領域以紅色圈出。

  1. 將JLabel拖放到Form Builder中。 Drag and drop a JLabel into the Form Builder.

  2. 打開JLabel的屬性菜單。輸入text字段的空字符串(「」)。單擊icon旁邊的省略號。 Open up the JLabel's properties menu. Click the ellipsis next to icon.

  3. 選擇外部圖像並單擊省略號。 Select External Image and click the ellipsis.

  4. 選擇圖像的選擇。在我的情況下,它是一個.png。 Select the image of choice.

  5. 請注意圖像出現在圖標預覽中。 Notice that the image appears in the icon preview.

  6. 關閉圖標菜單和屬性菜單,並注意圖像在Form Builder上顯示爲JLabel的圖標。 Close the icon menu and the properties menu, and notice that the image appears on the Form Builder.

感謝您接受一個非正統的SSCCE並預先感謝您的幫助。

+0

您可以在實例化'ImageIcon'的地方添加源代碼嗎? –

+0

將FrameView中的第156行從setVisible(false)更改爲setVisible(true),其餘更改我無法從我的魔球(低baterry)中看到,以便更快地發佈[SSCCE](http:// sscce 。org /) – mKorbel

+0

NetBeans GUIBuilder製作自己的源代碼,但是無論如何您仍然可以: 'jLabel1.setIcon(new Cursor.ImageIcon(「C:\\ NoSpace \\ Minesweeper \\ Minesweeper graphics \\ one.png 「));' – LastStar007

回答

1

我發現依靠Netbeans GUI生成器爲您做所有事情的難題是一個錯誤。

只需創建一個像下圖一樣的圖標抓取類,將圖標放入它的包中,然後使用「自定義代碼」而不是「圖像選擇器」。確保圖標在NB內不可見。但是如果它們在應用程序運行時出現,誰在乎。

package com.example.resource.icons; 

import javax.swing.ImageIcon; 

public class IconFetch { 

    private static IconFetch instance; 

    private IconFetch(){ 
    } 

    public static IconFetch getInstance() { 
     if (instance == null) 
      instance = new IconFetch(); 
     return instance; 
    } 

    public ImageIcon getIcon(String iconName) { 
     java.net.URL imgUrl = getClass().getResource(iconName); 
     if (imgUrl != null) { 
      return new ImageIcon(imgUrl); 
     } else { 
      throw new IllegalArgumentException("This icon file does not exist"); 
     } 
    } 

    public static final String MINESWEEPER_ONE = "one.png"; 
} 

用法:

IconFetch.getInstance().getIcon(IconFetch.MINESWEEPER_ONE); 

如果圖標仍然不嘗試此方法後顯示出來,那麼就有可能是錯誤的方式在您的形式奠定了組件(標籤是有,但你看不到它)。

希望這可以幫助,即使它是一個遠射。

2

我有同樣的問題,並且predi的解決方案也無法正常工作。然後我創建了一個包而不是一個文件夾,並在那裏添加了圖像,現在它可以工作。