我正在拉我的頭髮。這裏有很多像這樣的問題,但我無法實現。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()
。但這在這裏沒有任何區別。
我錯過了什麼?
'JLabel picLabel = new JLabel(new ImageIcon(myPicture));'爲什麼不在啓動時添加?無圖標或文字的標籤無論如何都是看不見的。 – 2014-10-19 21:42:54