简体   繁体   English

返回空指针的 png 上的 Java getClass().getResource

[英]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.我不确定我是否使用此代码指的是正确的位置,我尝试访问的图像标题为Flower0.png等。

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 .此类位于名为hangman.ui的 src 文件夹中,而.png文件位于名为Resources的目录文件夹中。

Perhaps getClass().getResource is not right?也许getClass().getResource不对?

This is my first time trying to put images into a GUI.这是我第一次尝试将图像放入 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.要在 GUI 上使用它,您可以使用 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根据 Maven: https : //maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

src/main/resources : Application/Library resources src/main/resources : Application/Library resources

Then I put the ICON in this Location:然后我把 ICON 放在这个位置:

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:现在使用 ICON 的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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