2012-11-20 71 views
0

我想在我的應用程序中顯示的圖像...JLabel的圖標未顯示

picture = new JLabel("No file selected"); 
    picture.setFont(picture.getFont().deriveFont(Font.ITALIC)); 
    picture.setHorizontalAlignment(JLabel.CENTER); 

    scrollPane.setViewportView(picture); 

    ImageIcon icon = new ImageIcon("map.jpg"); 
    picture.setIcon(icon); 
    if (picture.getIcon() != null)     // to see if the label picture has Icon 
     picture.setText("HERE IS ICON"); 

當我運行的代碼,只有「這裏是ICON」顯示的文本。 對不起,如果這個問題聽起來很愚蠢,但我真的不知道爲什麼圖像圖標不顯示:(

回答

2

你可以這樣做:

ImageIcon icon = createImageIcon("map.jpg", "My ImageIcon"); 

if (icon != null) { 
    JLabel picture = new JLabel("HERE IS ICON", icon, JLabel.CENTER); 
    picture.setFont(picture.getFont().deriveFont(Font.ITALIC)); 
    picture.setHorizontalAlignment(JLabel.CENTER); 

    scrollPane.setViewportView(picture); 
} 

的createImageIcon方法(在前面的代碼片段使用)查找指定的文件,如果該文件找不到返回該文件一個ImageIcon,或者爲null。這是一個典型的實現:

/** Returns an ImageIcon, or null if the path was invalid. */ 
protected ImageIcon createImageIcon(String path, 
              String description) { 
    java.net.URL imgURL = getClass().getResource(path); 
    if (imgURL != null) { 
     return new ImageIcon(imgURL, description); 
    } else { 
     System.err.println("Couldn't find file: " + path); 
     return null; 
    } 
} 
0

文件map.jpg可能與java文件不在同一個包(文件夾)。

1

您需要確保map.jpg作爲一個文件存在,如果您想確定(僅用於測試目的),請嘗試使用完整路徑。您擁有它的方式,路徑是相對於應用程序的啓動目錄

你可以仔細檢查其是否與此存在:

System.out.println(new java.io.File("map.jpg").exists()); 
+0

謝謝...現在得到它:)我多麼愚蠢:) – Ken