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

一个人想着一个人 提交于 2019-11-26 13:03:32

问题


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 ) {  }

回答1:


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 .



来源:https://stackoverflow.com/questions/3721706/embedding-resources-images-sound-bits-etc-into-a-java-project-then-use-those

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!