3

I have created a project, inside the project there is a folder named Source Packages, which contains my packages. I need images, and I want to copy them in a folder inside the project (or better inside the Source packages), so that when I create the .jar the image folder will be inside the jar file. How can I do that in NetBean?

Edit: I still can't figure it out, this is the code:

 Image star; 
 InputStream stream = getClass().getResourceAsStream("images/star.png");
 star= ImageIO.read(stream);

It doesn't work, I get the error "IllegalArgumentException input==null"

the folder "images" is inside the folder of the project "Game", if I try with this code:

Image star; 
InputStream stream = getClass().getResourceAsStream("images/star.png");
star= Toolkit.getDefaultToolkit().getImage("images/star.png");

it works, what am I doing wrong with the InputStream?

AR89
  • 3,548
  • 7
  • 31
  • 46

2 Answers2

2

You can just copy/paste your images into your package or into the folder which is represented by the package. When you want to access the images:

InputStream stream = getClass().getResourceAsStream("/com/my/pkg/my_image.png");

See this SO question for some more examples:

how to add image from spectified package into label, frames etc

Edit: ClassLoader.getResourceAsStream(String) will find any resource that is located in the package you specify for the path. For example, if you want to get an image that resides in com.my.pkg.a from a class that resides in com.my.pkg.b:

// From com.my.pkg.b.MyClass
InputStream stream = getClass().getResourceAsStream("/com/my/pkg/a/my_image.png");

Notice that the path specified goes to package a. This will get find the image even though it resides in a different package. See the javadoc for ClassLoader.getResource(), which is what is used internally, for more detailed information.

Community
  • 1
  • 1
Jonathan Spooner
  • 7,682
  • 2
  • 34
  • 41
0
  1. create a folder in your root project folder ("resources" for instance)
  2. in the project properties dialog, "Sources" page, click on the "Add Folder..." button that is at the right of the "Source package folders" table
  3. Select your newly created folder, click OK
  4. Change the label for your folder in the "Source package folders" table ("Resource Packages" for instance)

The files in that folder will be included in the jar of your application.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97