-1

I have this code but I don't know how to load in the image stone.png so I can use it.

package mine.mine.mine;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MainGame {
    private static void showGUI()
    {   JFrame frame = new JFrame("Mine Mine Mine");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel emptyLabel = new JLabel("");
    emptyLabel.setPreferredSize(new Dimension(496, 496));
    frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    BufferedImage img = null, diamond = null, emerald = null, gold = null, lapis = null, iron = null, redstone = null, coal = null; //Ignore these.
    try {
        img = ImageIO.read(new File("stone.png")); //Main problem is here. Used debug method on line 27.
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "ERROR: The game has corrupted/missing files. Please redownload the game.", "Mine Mine Mine", JOptionPane.ERROR_MESSAGE);
        JOptionPane.showMessageDialog(null, e.getStackTrace());
    }



}
    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
            }
        });
    }


}

I want to display stone.png on the JLabel or JFrame, this is my first time trying this so please don't call me a noob. ;)

Lewis Holmes
  • 15
  • 1
  • 10

1 Answers1

2

Images (or anything) stored within a Jar file can't be access like a File, instead you need to use Class#getResource which will return a URL which can be used by many parts of the API to load these resources.

Where a part of the API doesn't accept a URL, you can use Class#getResourcesAsStream which returns an InputStream instead.

Something like...

img = ImageIO.read(MainGame.class.getResource("stone.png"));

This assumes the stone.png is the default/top level directory of the jar file, if it's within a subdirectory, you will need to specify the full path from the root of the jar file

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366