2011-11-26 79 views
0

所以我試圖在大學裏爲一個項目製作一個小遊戲。我有一個圖像類加載圖像等我知道這個類的作品,因爲我測試了它,當我做到了。但後來我決定使用一個表單製造商,在這種情況下,WindowsBuilder Pro製作的表單更好,然後我就可以編寫代碼。我現在試圖調用一個函數,理論上它會加載調用圖像類並加載圖像,然後將該圖像作爲圖像添加到jPanel中的標籤。但我什麼都沒有。任何幫助?ImageIcon無法加載

private void loadres(){ 
    String PROGRAM_DIRECTORY = "E:/WordGame/bin/Images/"; 

    Functions.Resources rs = new Functions.Resources(); 
    rs.loadResources(); 
    Functions.ImageLib iL = rs.getIL(); 

    try { 
     BGImage = new JLabel(new ImageIcon(iL.mergeImages(iL.getImageArray(0),iL.getImage(PROGRAM_DIRECTORY + "Astroid1Image.png")))); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    BGImage.revalidate(); 
    BGImage.repaint(); 
} 

這裏是圖片的功能,我使用:

public class ImageLib { 

private ArrayList<BufferedImage> BIArray = new ArrayList<BufferedImage>(); 

public ImageLib(){ 
} 

public BufferedImage getImage(String ref){ 
    BufferedImage Bi = null; 

    try{ 
     Bi = ImageIO.read(new File(ref)); 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return Bi; 
} 

public BufferedImage resizeImage(BufferedImage Bi, int nW, int nH){ 
    int w = Bi.getWidth(); 
    int h = Bi.getHeight(); 

    BufferedImage nBi = new BufferedImage(nW, nH, Bi.getType()); 
    Graphics2D g = nBi.createGraphics(); 
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 

    g.drawImage(Bi,0,0,nW,nH,0,0,w,h,null); 
    g.dispose(); 

    return nBi; 
} 

public void addToArray(BufferedImage img){ 
    BIArray.add(img); 
} 

public BufferedImage getImageArray(int index){ 
    return (BufferedImage) BIArray.get(index); 
} 

public BufferedImage mergeImages(BufferedImage I1, BufferedImage I2) throws IOException{ 
    int w = Math.max(I1.getWidth(), I2.getWidth()); 
    int h = Math.max(I1.getHeight(), I2.getHeight()); 
    BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); 

    Graphics g = combined.getGraphics(); 
    g.drawImage(I1, 0, 0, null); 
    g.drawImage(I2, 0, 0, null); 
    g.dispose(); 

    return combined; 
} 

}

+0

可能有助於告訴你,佈局框架/面板是grouplayout,並且BGImage是我在WYSIWUG編輯器WBP中添加的標籤。該標籤的寬度爲501,高度爲250或接近。 – Tempus35

+2

將你的圖片放到你的src文件夾中,試試這個^^: ClassLoader cldr = this.getClass()。getClassLoader(); java.net.URL imageURL = cldr.getResource(「path/to/your/images/picture.gif」); ImageIcon imgIcon = new ImageIcon(imageURL); – hungneox

+0

請學習java命名約定並堅持使用它們 – kleopatra

回答

2

這裏是我的回答^^

ClassLoader cldr = this.getClass().getClassLoader(); 
java.net.URL imageURL = cldr.getResource("path/to/your/images/picture.gif"); 
ImageIcon imgIcon = new ImageIcon(imageURL); 
+0

這是一個不錯的主意,給我的文件路徑更容易,但它仍然不是呈現圖像。問題不在於如何獲取圖像,而是如何獲取圖像。 – Tempus35

+0

我現在工作,加入面板錯誤 – Tempus35

+0

@ Tempus35這是我用JFrame的代碼; ImageIcon imgIcon = new ImageIcon(getClass()。getResource(「/ com/eproject/dcl/images/lock.png」)); setIconImage(imgIcon.getImage()); – hungneox