有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我不确定我是否用这段代码指的是正确的位置,我试图访问的图像标题是Flower0.png等等

它们与本项目的其余代码位于同一目录中。 此类位于名为hangman.ui的src文件夹中,.png文件位于名为Resources的目录文件夹中

也许getClass().getResource是不对的

这是我第一次尝试将图像放入GUI

非常感谢您的帮助

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) 个答案

  1. # 1 楼答案

    你说这些图片在一个叫做“资源”的文件夹里?您可以加载这样的图像:

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

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

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

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