0

I am creating a very basic game in Java for an English project that's due in a few days (any answers are appreciated!).

I am having problems with compiling and loading images: in my IDE, IntelliJ, I can easily load images but with a direct path such as src/main/resources/assets/image.png. However I have my program structured so it works with Gradle and really I should only need assets/image.png.

The main issue however, is when I run ./gradlew jar to compile it into a executable .jar file, it never finds the image regardless of what kind of path I use.

Could anyone help give a few suggestions? I've tried many methods with ImageIO and such. I couldn't find a solution that worked on StackOverflow.

Here's my code: (some irrelevant things like KeyAdapters ommitted. This is really messy and bad code but I just would like for it to be functional)

public class Game implements Runnable {

    final int WIDTH = 1000;
    final int HEIGHT = 700;

    JFrame frame;
    Canvas canvas;
    BufferStrategy bufferStrategy;

    public Game() {
        frame = new JFrame("Hamlet Game by Brian Shin");

        JPanel panel = (JPanel) frame.getContentPane();
        panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        panel.setLayout(null);

        canvas = new Canvas();
        canvas.setBounds(0, 0, WIDTH, HEIGHT);
        canvas.setIgnoreRepaint(true);

        panel.add(canvas);

        canvas.addMouseListener(new MouseControl());
        canvas.addKeyListener(new KeyControl());

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);

        canvas.createBufferStrategy(2);
        bufferStrategy = canvas.getBufferStrategy();

        canvas.requestFocus();
    }

    //Key adapter and Mouse stuff here

    Sprite background;
    Sprite hamlet;

    public void initGame() {

        // TESTING
        /*ImageIcon bg = new ImageIcon("src/main/resources/bg.png");
        background = new Sprite(bg.getImage(), 0, 0);

        ImageIcon hammy = new ImageIcon("src/main/resources/hamlet.png");
        hamlet = new Sprite(hammy.getImage(), 300, 300); */

        BufferedImage bg;
        BufferedImage hammy;
        try {
            bg = ImageIO.read(new File("src/main/resources/assets/bg.png")); // TODO: get it working with .jar compiler
            hammy = ImageIO.read(new File("src/main/resources/assets/hamlet.png")); // src/main/resources/assets
            background = new Sprite(bg, 0, 0);
            hamlet = new Sprite(hammy, 300, 300);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    long desiredFPS = 60;
    long desiredDeltaLoop = (1000*1000*1000)/desiredFPS;
    boolean running = true;

    public void run() {

        long beginLoopTime;
        long endLoopTime;
        long currentUpdateTime = System.nanoTime();
        long lastUpdateTime;
        long deltaLoop;

        initGame();

        while(running) {
            beginLoopTime = System.nanoTime();

            render();

            lastUpdateTime = currentUpdateTime;
            currentUpdateTime = System.nanoTime();
            update((int) ((currentUpdateTime - lastUpdateTime)/(1000*1000)));

            endLoopTime = System.nanoTime();
            deltaLoop = endLoopTime - beginLoopTime;

            if(deltaLoop > desiredDeltaLoop) {
                //Do nothing.
            } else {
                try {
                    Thread.sleep((desiredDeltaLoop - deltaLoop)/(1000*1000));
                } catch(InterruptedException e) {
                    //Do nothing.
                }
            }
        }
    }

    private void render() {
        Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
        g.clearRect(0, 0, WIDTH, HEIGHT);
        g.drawImage(background.getImage(), background.getX(), background.getY(), null);
        render(g);
        g.dispose();
        bufferStrategy.show();
    }

    /**
     * Update method.
     */
    protected void update(int deltaTime) {
    }

    /**
     * Main rendering method.
     */
    protected void render(Graphics2D g) {
        g.drawImage(hamlet.getImage(), hamlet.getX(), hamlet.getY(), null);
    }

    public boolean collision(Sprite s) {
        return (s.getX() < 0 || s.getY() < 0 || s.getX() > (WIDTH - 30) || s.getY() > (HEIGHT - 45));
    }

    public Direction getCollDir(Sprite s) {
        if(s.getX() < 0) {
           return Direction.LEFT;
        } else if(s.getY() < 0) {
            return Direction.UP;
        } else if(s.getX() > (WIDTH - 30)) {
            return Direction.RIGHT;
        } else if(s.getY() > (HEIGHT - 45)) {
            return Direction.DOWN;
        } else {
            return Direction.NONE;
        }
    }

    public static void main(String [] args) {
        Game ex = new Game();
        new Thread(ex).start();
    }

} 

The errors produced are:

javax.imageio.IIOException: Can't read input file!
        at javax.imageio.ImageIO.read(Unknown Source)
        at Game.initGame(Game.java:151)
        at Game.run(Game.java:172)
        at java.lang.Thread.run(Unknown Source)
Exception in thread "Thread-2" java.lang.NullPointerException
        at Game.render(Game.java:201)
        at Game.run(Game.java:177)
        at java.lang.Thread.run(Unknown Source)

1 Answers1

0

You should use ImageIO.read(InputStream input) instead of ImageIO.read(File file).
Then pass the file as a stream by loading it as a classpath resource: Game.class.gerResourceAsStream("/bg.png");

If the image is located under a directory inside the jar, just append the the directory path in front of the filename.

Marinos An
  • 9,481
  • 6
  • 63
  • 96