1

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

    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
jessicaeden
  • 15
  • 1
  • 1
  • 4

2 Answers2

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.

ultddave
  • 188
  • 1
  • 11
  • 1
    The filenames of resources do NOT have to start with "/" (as asserted in another answer); if they do start with /, then the path is relative to some path on the classpath; if they do not, they are relative to the directory in which that class lives. So the "x.png" without any slashes would be looked for in the same directory as the class on which getResource is called, "y/x.png" would be looked for in a directory y that is a subdirectory under the directory where the class lives. – arcy May 26 '13 at 20:48
0

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")
    )
);
joseluisbz
  • 1,491
  • 1
  • 36
  • 58