2014-10-19 154 views
0

我正在拉我的頭髮。這裏有很多像這樣的問題,但我無法實現。Java將圖像添加到JPanel。爲什麼圖片不顯示?

我想添加一個圖像到現有的JPanel。問題是讓圖像在JPanel中可見。該代碼運行,但圖像是無處..

這裏是我的代碼:

private void loadImgBtnActionPerformed(java.awt.event.ActionEvent evt) {           
    // TODO add your handling code here:  
    int returnVal = fileChooser.showOpenDialog(this); 
    if (returnVal == JFileChooser.APPROVE_OPTION) 
    { 

     File file = fileChooser.getSelectedFile(); 
     BufferedImage myPicture = null; 
     try { 
      myPicture = ImageIO.read(file); 
     } catch (IOException ex) { 
      Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     JLabel picLabel = new JLabel(new ImageIcon(myPicture)); 
     imagePnl2.add(picLabel); 
     imagePnl2.repaint(); 
     imagePnl2.revalidate(); 

    } 
    else 
    { 
     System.out.println("File access cancelled by user."); 
    } 

} 

this question的問題是缺少revalidate()。但這在這裏沒有任何區別。

我錯過了什麼?

+0

'JLabel picLabel = new JLabel(new ImageIcon(myPicture));'爲什麼不在啓動時添加?無圖標或文字的標籤無論如何都是看不見的。 – 2014-10-19 21:42:54

回答

2

在這個問題中,問題是缺少revalidate()。但這在這裏沒有任何區別。

訂單很重要。代碼應該是:

panel.add(...); 
panel.revalidate(); 
panel.repaint(); 

revalidate()調用佈局管理器,然後確定組件的大小和位置。默認情況下,組件的大小爲(0,0),因此如果首先調用repaint(),則不需要繪製任何東西。

此外,更簡單的解決方案是在創建GUI時爲面板添加一個空標籤。然後,當你想添加的圖片,你可以這樣做:

label.setIcon(...); 

的setIcon()來的方法自動進行重新驗證()和重繪()爲您服務。

+0

更改順序不起作用。 label.setIcon做到了!非常感謝! – Forza 2014-10-19 21:51:31