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

    }
}
4

2 回答 2

1

你说图像在一个名为“资源”的文件夹中?您可以像这样加载图像:

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

要在 GUI 上使用它,您可以使用 JLabel。

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

然后例如将标签添加到面板。

于 2013-05-26T20:35:03.830 回答
0

对我来说工作...

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

src/main/resourcesApplication/Library resources

然后我把ICON放在这个位置:

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

清洁和建造。您可以在此处查看获取文件的位置....

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

现在使用 ICON 的示例:

button.setIcon(
    new javax.swing.ImageIcon(
        getClass().getClassLoader().getResource("usedPictures/Open.png")
    )
);
于 2020-09-17T00:09:54.217 回答