我对这个很抓狂。这里有很多这样的问题,但我无法让它发挥作用。
我正在尝试将图像添加到现有的 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()
。但这在这里没有什么区别。
我错过了什么?
最佳答案
In this question the problem was the missing revalidate(). But that makes no difference here.
顺序很重要。代码应该是:
panel.add(...);
panel.revalidate();
panel.repaint();
revalidate() 调用布局管理器,后者又确定组件的大小和位置。默认情况下,组件的大小为 (0, 0),因此如果您首先调用 repaint(),则没有任何内容可绘制。
此外,一个更简单的解决方案是在创建 GUI 时向面板添加一个空标签。然后当你想添加图像时,你可以这样做:
label.setIcon(...);
setIcon() 方法会自动为您执行 revalidate() 和 repaint()。
关于Java 将图像添加到 JPanel。为什么图像不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455633/