0

Whenever I try to add an image to my JPanel I get an NPE. (The error is when I initialize a new ImageIcon!)

What I've tried:

  • Class loader
  • Main class's get resource
  • '/' before path and without '/' before path

Code in main class:

public class Main {
    public static void main(String[] args) {
        GameWindow game = new GameWindow();

        game.setSize(1280, 720);
        game.center();

        game.addImage(new ImageIcon(Main.class.getResource("player.png")).getImage(), 0, 0);

        game.setVisible(true);
    }
}

Inside the engine GameWindow class:

public class GameWindow {
    private final JFrame frame = new JFrame("Game Window");
    private final JPanel board = new JPanel();

    public GameWindow() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void addImage(Image image, int x, int y) {
        board.getGraphics().drawImage(image, x, y, null);
    }

    public void center() {
        frame.setLocationRelativeTo(null);
    }

    public void setVisible(boolean visible) {
        if (visible) {
            if (!board.isVisible()) {
                board.setVisible(true);
                frame.add(board);
            }
        }
        frame.setVisible(visible);
    }

    public void setSize(int x, int y) {
        frame.setSize(x, y);
    }
}

Here's what the file path looks like before building it into a JAR and running it. File path image Any help would be appreciated, I've spent so long (1 day + 1/2) trying to find an answer.

  • `board.getGraphics()` is a bad idea and is not how custom paint works. You'll want to look at [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/) and [Painting in AWT and Swing](https://www.oracle.com/java/technologies/painting.html) to get a better idea of how custom painting works and possibly [How to Use Labels](https://docs.oracle.com/javase/tutorial/uiswing/components/label.html) – MadProgrammer Apr 11 '21 at 23:52
  • Unjar the resulting jar (it's just a zip file) and check to see if the image is contained within the Jar. You should be making uses of packages/folders to help seperate logic work units – MadProgrammer Apr 11 '21 at 23:54
  • It is inside of the JAR file. –  Apr 12 '21 at 00:20
  • Likely issue is the fact that `getGraphics` can return `null`, again, which is why you shouldn't be using it – MadProgrammer Apr 12 '21 at 02:18

0 Answers0