Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding resources (images, sound bits, etc) into a Java project then use those resources

I have searched for a method of embedding a resource in a java project (using Eclipse v3.6.0) then using that embedded resource within a control (e.g., JLabel). I have seen methods of referencing resources from the file system. Once the project has been developed I would like to publish the application as an executable. It should be noted these executables will be deployed/launched to Windows, *NIX, and Linux platforms.

I know this can be done in the Visual Studio world, but I'm very unfamiliar how to do this in Java/Eclipse IDE. As a side question, how do I get Eclipse to create the project as a executable so it can be launched?

Any help is greatly appreciated.

Mark

UPDATE 1:

Based upon BalusC's response, I wanted to share the code I have to resolve my problem. My classes are under the package of "Viking.Test" and then I placed the image file under the package "Viking.Test.Resources". This is all done within Eclipse to import the image into the project.

  1. I imported the image by right-clicking on the Project -> Import -> General/File System for the import source.
  2. Selected the folder which contained the image to import
  3. Selected "Project/src/Viking/Test/Resources" for the 'Into folder' parameter
  4. Didn't change any of the options and clicked "Finished"

In the source file I added the following code to insert the image into a JLabel (LblLogo)

try
{
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  InputStream input = classLoader.getResourceAsStream(
    "Viking/Test/Resources/MyImage.jpg");
  Image logo = ImageIO.read(input);
  LblLogo = new JLabel( new ImageIcon( logo ) );
  LblLogo.setBounds(20, 11, 210, 93);
  getContentPane().add(LblLogo);
}
catch ( IOException e ) {  }
like image 827
lordhog Avatar asked Sep 15 '10 20:09

lordhog


1 Answers

Just put those resources in the source/package structure and use ClassLoader#getResource() or getResourceAsStream() to obtain them as URL or InputStream from the classpath by the full qualified package path.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("/image.gif"); // ... 

Or if it is in the same package as the current class, you can also obtain it as follows:

InputStream input = getClass().getResourceAsStream("image.gif"); 

As a side question, how do I get Eclipse to create the project as a executable so it can be launched.

Rightclick Java Project > Export > Runnable JAR File .

like image 82
BalusC Avatar answered Sep 20 '22 15:09

BalusC