简体   繁体   中英

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

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"));

    }
}

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.

For me Works...

According to Maven: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

src/main/resources : Application/Library resources

Then I put the ICON in this Location:

PROJECTNAME\src\main\resources\usedPictures\
--Open.png

Clean and Build. And you can check here the location where the file will be get....

PROJECTNAME\target\classes\usedPictures\
--Open.png

Now the Example using the ICON:

button.setIcon(
    new javax.swing.ImageIcon(
        getClass().getClassLoader().getResource("usedPictures/Open.png")
    )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM