【问题标题】:PNGs not displaying on JPanelPNG不显示在JPanel上
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    为什么要创建 ImagePanel。您的绘画代码正在以原始大小绘制图像。只需使用带有 ImageIcon 的 JLabel,无需自定义绘画。

    【讨论】:

    • 感谢您的建议。我尝试使用 JLabel,但出现了同样的问题。 JPEG 与 JLabel 一起工作正常,但 PNG 不显示。
    猜你喜欢
    • 2019-07-08
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    • 2012-08-08
    • 2013-04-03
    相关资源
    最近更新 更多