我的项目中有一个图像文件。层次结构如下所示:

我正在尝试使用以下代码将Manling.png读入Manling.java:

public BufferedImage sprite;

public Manling()
{
    try
    {
    File file = new File("resources/Manling.png");
    sprite = ImageIO.read(file);
    } catch (IOException e) {}

    System.out.println(sprite.toString()); //This line is to test if it works
}

我总是在NullPointerException语句上得到一个println,所以我认为路径是错误的。我尝试将图片移到项目中的其他位置,并尝试更改文件路径(例如'mine/resources/Manling.png'和'/resources/Manling.png')。有任何想法吗?

如果您想要一个完整的可编译示例,请尝试以下示例:
package minesscce;

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.URL;

public class Mine extends JFrame
{
private BufferedImage sprite;

public static void main(String args[])
{
    Mine mine = new Mine();
}

public Mine()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setSize(800, 600);
    setExtendedState(Frame.MAXIMIZED_BOTH);
    setBackground(Color.WHITE);

    try
    {
        File file = new File("resources/Manling.png");
        sprite = ImageIO.read(file);
    } catch (IOException e) {}

    System.out.println(sprite.toString());
}

public void paint(Graphics g)
{
    g.translate(getInsets().left, getInsets().top);
    Graphics2D g2d = (Graphics2D)g;

    g2d.drawImage(sprite, 0, 0, this);
    Toolkit.getDefaultToolkit().sync();
    g2d.dispose();
}

}

只需使用所需的任何图像,像这样设置项目:

最佳答案

尝试

ImageIO.read(Mine.class.getResource("../minesscce.resources/Manling.png"));

这是一个例子:
  • 层次结构


  • 结果


  • 这是代码 ...
    public final class ImageResourceDemo {
        private static BufferedImage bi;
    
        public static void main(String[] args){
            try {
                loadImage();
    
                SwingUtilities.invokeLater(new Runnable(){
                    @Override
                    public void run() {
                        createAndShowGUI();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        private static void loadImage() throws IOException{
            bi = ImageIO.read(
                    ImageResourceDemo.class.getResource("../resource/avatar6.jpeg"));
        }
    
        private static void createAndShowGUI(){
            final JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setBackground(Color.WHITE);
            frame.add(new JLabel(new ImageIcon(bi)));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
    

    09-05 13:47