PNG未显示在JPanel上

时间:2013-12-11 15:36:14

标签: java swing jpanel png jpeg

我有一个扩展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时不显示任何内容。

2 个答案:

答案 0 :(得分:0)

  

当加载的图像是JPEG时,相同的程序工作正常,但如果图像是PNG,则图像不会显示

加载.jpg或.png文件的代码没有区别。如果路径正确,文件没有损坏,则应加载。

为什么要创建ImagePanel。您的绘画代码正在以原始大小绘制图像。只需将JLabel与ImageIcon一起使用,就不需要自定义绘画。

答案 1 :(得分:0)

似乎问题是alpha问题的结果。我必须返回并确保检查所有可以修改图像的功能是否已设置为与alpha一起正常工作。很明显我把它搞砸了一些。