Java getClass().getResource on a png returning Null Pointer

只愿长相守 提交于 2019-12-02 16:50:08

问题


I am not sure if I am referring to the right location with this code, the images I am trying to access are titled Flower0.png etc.

They are located in the same directory as the rest of my code for this project. This class is in a src folder called hangman.ui and the .png files are located in a directory folder called Resources.

Perhaps getClass().getResource is not right?

This is my first time trying to put images into a GUI.

Help is much appreciated!

public WiltingFlowerRendererRemix(HangmanLogic logic) 
{
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    imageLabel = new JLabel();
    panel.add(imageLabel, BorderLayout.CENTER);

    int numberOfImages = 10;

    images = new ImageIcon[numberOfImages];
    for (int i = 0; i < numberOfImages; i++)
    {
        images[i] = new ImageIcon(getClass().getResource("Flower"+Integer.toString(i) + ".png"));

    }
}

回答1:


You say the images are in a folder called "Resources"? You can load images like this then:

BufferedImage image = ImageIO.read(getClass().getResource("/Resources/Flower0.png"));
ImageIcon icon = new ImageIcon(image);

To use it on the GUI you can use a JLabel.

JLabel label = new JLabel();
label.setIcon(icon);

And then add the label to a panel for example.



来源:https://stackoverflow.com/questions/16763356/java-getclass-getresource-on-a-png-returning-null-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!