【发布时间】:2013-12-29 16:08:19
【问题描述】:
我有一个扩展 JFrame 的类。它使用以下代码将 180 张图像加载到数组中
ImageIO.read((getClass().getClassLoader().getResourceAsStream("render/"+constructImageFilename(i))));
constructImageFilename 函数为每个文件创建文件名,该文件位于 src 中名为“render”的文件夹中。它工作正常。
然后该类使用数组中的第一个图像创建一个 ImagePanel。它添加 ImagePanel,设置它的大小,然后显示出来。
ImagePanel 类是 JPanel 的扩展类。
public class ImagePanel extends JPanel{
private BufferedImage img; //This is the image that the ImagePanel contains.
public ImagePanel() {
super();
}
public void setImage(BufferedImage i) {img=i;} //Mutator for the image.
public BufferedImage getImage() {return img;} //Accessor for the image.
public void paint(Graphics g) {
super.paint(g); //Paint the normal JPanel stuff.
((Graphics2D)g).drawImage(img,null,0,0); //Draw the image.
}
}
当加载的图像是 JPEG 时,相同的程序可以正常工作,但如果图像是 PNG,则图像不会显示。它只是显示 JPanel 的默认灰色。没有运行时错误,并且图像被清楚地加载,因为在 BufferedImage 上调用 getRGB 会返回值。
什么可能导致 PNG 不显示?
更新:我尝试使用 JLabel 而不是 ImagePanel 类。 JLabel 似乎也有同样的问题。当我使用 JPEG 时它显示,但当我使用 PNG 时不显示任何内容。
【问题讨论】:
-
不,您的问题含糊不清:您说的是
The ImagePanel class is a class that extends JFrame.,但我们看到它扩展了JPanel。再次声明It adds the ImagePanel, sets its size, and then shows up.:我有难闻的气味:您是否使用setSize(Dimension)来设置您认为正确的尺寸^~ ;) -
抱歉含糊不清。我的意思是JPanel。另外,当我说“设置它的大小”时,我的意思是扩展 JFrame 的类设置了它自己的大小。
标签: java swing jpanel png jpeg