Domanda

I have had this problem for about a year, why when I pack my JAR file with a res folder (say for a game), it packs the folder, but doesn't read it? I have tried making the res folder a package, on its own, and I have tried every way to access the image:

Toolkit.getDefaultToolkit().getImage("res/player.png");
Image player = new ImageIcon("res/player.png").getImage();
Image player = ImageIO.read(new File("res/player.png"));

But they just don't work... I need help, and I have no idea how to fix this..

È stato utile?

Soluzione

Read the javadoc of all these methods. They all take the name of a file as argument. So they will look on your hard drive, for the file <current directory>/res/player.png.

But your image is not a file on the hard drive. It's a resource inside your jar file. You want to load this resource the same way as the classes in this jar file are loaded: using the ClassLoader. What you need is

ImageIcon image = new ImageIcon(SomeClassOfYourApp.class.getResource("/res/player.png"));

or

ImageIcon image = new ImageIcon(getClass().getClassLoader().getResource("res/player.png"));

That assumes that the path of the file inside the jar is /res/player.png.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top