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.
- I imported the image by right-clicking on the Project -> Import -> General/File System for the import source.
- Selected the folder which contained the image to import
- Selected "
Project/src/Viking/Test/Resources
" for the 'Into folder' parameter - Didn't change any of the options and clicked "Finished"
In the source file I added the following code to inse开发者_如何学Gort 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 ) { }
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 .
精彩评论