0
votes

I have a class that extends JFrame. It loads 180 images into an array using the following code

ImageIO.read((getClass().getClassLoader().getResourceAsStream("render/"+constructImageFilename(i))));

The constructImageFilename function creates the filename for each file, located within a folder in the src called "render." It works fine.

The class then creates an ImagePanel with the first image in the array. It adds the ImagePanel, sets its size, and then shows up.

The ImagePanel class is a class that extends 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.
    }
}

The same program works fine when the images loaded in are JPEGs, but the image doesn't diplay if the images are PNGs. It simply shows the default gray of the JPanel. There are no runtime errors, and the image was clearly loaded, as calling getRGB on the BufferedImage returns values.

What could be causing the PNG not to display?

UPDATE: I tried using a JLabel instead of my ImagePanel class. The JLabel seems to have the same problem. It displays when I use a JPEG, but displays nothing when I use a PNG.

2
No, your question is ambiguous: you said The ImagePanel class is a class that extends JFrame. but we are seeing it extends JPanel. Again you have statement It adds the ImagePanel, sets its size, and then shows up.: i am having bad smells: Are you using setSize(Dimension) to set the size which you think is the proper way right ^~ ;)Sage
Sorry about the ambiguity. I meant JPanel. Also, when I said "sets it's size" I meant that the class that extends JFrame sets its own size.fakedad

2 Answers

0
votes

The same program works fine when the images loaded in are JPEGs, but the image doesn't diplay if the images are PNGs

There is not difference in the code for loading a .jpg or .png file. If the path is correct the file is not damaged it should load.

Why are you creating an ImagePanel. Your painting code is drawing the image at its original size. Just use a JLabel with an ImageIcon and there is no need for custom painting.

0
votes

It seems that the problem was the result of problems with alpha. I had to go back and make sure to check that all of the functions that could modify the image were set up to work properly with alpha. Evidently I had messed it up in some of them.