I right-click on my project, then select Export, then select Runnable Jar File And then Export, but when I launch it, it just has a clear screen, but in Eclipse it shows my image.
How would I fix this?
I've tried numerous posts and did everything they said to do, but when I try to put the .jar file in the images folder and then launch the jar it still launches with no background image.
I had the same issue. It took me a bit to actually find an answer. Here is the answer I found. Save your images in a seperate folder somewhere in your src folder and add to build path. Then, since the images are static you can just access it like this: blueSprite = ImageLoader.blueSprite; Don't forget to call ImageLoader.loadImages() too.
final public class ImageLoader {
public static BufferedImage blueSprite;
public static InputStream load(String path) {
InputStream input = ImageLoader.class.getResourceAsStream(path);
if (input==null) {
input=ImageLoader.class.getResourceAsStream("/"+path);
}
return input;
}
public static void loadImages() {
try {
blueSprite= ImageIO.read(ImageLoader.load("explosionSheetBlueShort.png"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR LOADING IMAGES. CONTACT ADMIN FOR SUPPORT");
e.printStackTrace();
}
}
}
Related
I am trying to use resource bundle in my project. i am new for development. is it professional way to put property files inside src/ folder i mean inside jar.
Also i have tried by placing my propert [AppProp] outside of the src folder [/resources/properties/AppProp]. I have added Add Class Folder from build path eclipse. I am trying to run this in eclipse. But it says Can't find bundle for base name. Please see my below code. Please provide any suggestion.
public class PropertyReader {
private String bundleName = null;
ResourceBundle resourceBundle = null;
public PropertyReader(String bundle){
this.bundleName = bundle;
loadProperty();
}
public void loadProperty(){
try{
resourceBundle = ResourceBundle.getBundle(bundleName);
} catch(Exception e){
e.printStackTrace();
}
}
public static void main(String a[]){
try{
PropertyReader pr = new PropertyReader("resources/properties/AppProp");
} catch(Exception e){
e.printStackTrace();
}
}
}
You don't need to change the code. But make sure following
1) You are providing the correct file path.
2) File type must be .properties in your case it should be be like AppProp.properties
There are lot of techniques/standards to organize your source files and code.
But for now above points are the solution of your problem.
I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:
To create a directory several levels deep when one or more of the
parent directories might not yet exist, you can use the convenience
method, createDirectories(Path, FileAttribute). As with the
createDirectory(Path, FileAttribute) method, you can specify an
optional set of initial file attributes. The following code snippet
uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories
are created, as needed, from the top down. In the foo/bar/test
example, if the foo directory does not exist, it is created. Next, the
bar directory is created, if needed, and, finally, the test directory
is created.
It is possible for this method to fail after creating some, but not
all, of the parent directories.
Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
}
public void createFile(String rootDir) {
String filePath = rootDir;
try {
if(rootDir.contains(File.separator)){
filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
}
File file = new File(filePath);
if(!file.exists()) {
System.out.println(file.mkdirs());
file = new File(rootDir);
System.out.println(file.createNewFile());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
So I've tried various reading various fixes for this problem on stack exchange most say to use getResourceAsStream() method, which I have done.
This is my Resource input method for the Jar .
import java.io.InputStream;
public class ResourceLoader {
public static InputStream load(String path){
InputStream input = ResourceLoader.class.getResourceAsStream(path);
if(input == null){
input = ResourceLoader.class.getResourceAsStream("/" + path);
}
return input;
}
}
This is then used in my ImageLoader class.
public class ImageLoader {
public BufferedImage load(String path){
try {
// return ImageIO.read(getClass().getResource(path));
return ImageIO.read(ResourceLoader.load(path));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
and the images are loaded in the main program using
ImageLoader loader = new ImageLoader();
spriteSheet = loader.load("/spritesheet.png");
Now in eclipse the game runs and loads all images perfectly fine.
But what I want to do is export it to Jar, which I have done using some tutorials and
have succeeded in exporting it with the resource folder which contains my images that are used. But when I try and run the .jar file this error pops up in the cmd line.
Exception in thread "Thread-2" java,lang.IllegalArgumentException: input == null
!
at javax.imageio.ImageIO.read<Image.IO.java:1348>
at gfx.ImageLoader.load<ImageLoader.java:15>
at man.Gaim.init(Game.java:100>
at main.Game.run<Game.java:150>
at java.lang.Thread.run<Thread.java:722>
So what I'm gathering is that the image file locations are not being read properly or I inputed them wrong somehow which is returning null and none of the images are loading. When the .Jar is run the Panel appears but nothing is painted to it and that error is given.
This program does work perfectly in eclipse with no errors and all images loading.
EDIT 1:
Robermann your solution for the getClass().getClassLoader().getResourceAsStream(path)) works. The only thing is I need to have the image files in a folder with the jar.
For instance I have
Folder:
---File.Jar
---Images.png
---ImageFolder
-------More imgaes in imagefolder.png
I can load all the images when they are located like that. My actual question was when i export a .Jar the Images are also located inside is it possible to just use the images that are located inside the .jar? Or do I have to pack the imgaes in a folder alongside the jar as above, It works but i was more looking for a runnable .Jar that i could just transer to tohers without having them also need the images outside the .jar.
The question of how to load classpath resources is quite recurring, and a bit confusing for a Java newbie: some answers suggest class.getClassLoader().getResourceAsStream, others class.getResourceAsStream, although they have a slight different semantic:
class.getResourceAsStream does a path translation
class.getClassLoader().getResourceAsStream does not translate the path
For better show the difference, I'm going to propose the following test class, which in 4 different ways try to load the same resource (an image), only 2 working depending on the used path. The Jar content-tree is:
The class:
package image;
import java.io.InputStream;
public class ImageLoader {
public static void main(String[] args ){
String cmd = null;
InputStream is = null;
final String image = "save.png";
if("test1".equals(args[0])){
cmd = "ImageLoader.class.getClassLoader().getResourceAsStream(\""+image+"\")";
is = ImageLoader.class.getClassLoader().getResourceAsStream(image); //YES, FOUND
}else if("test2".equals(args[0])){
cmd = "ImageLoader.class.getResourceAsStream(\""+image+"\")";
is = ImageLoader.class.getResourceAsStream(image); //NOT FOUND
}else if("test3".equals(args[0])){
cmd = "ImageLoader.class.getResourceAsStream(\"/"+image+"\")";
is = ImageLoader.class.getResourceAsStream("/"+image); //YES, FOUND
}else if("test4".equals(args[0])){
cmd = "ImageLoader.class.getClassLoader().getResourceAsStream(\"/"+image+"\")";
is = ImageLoader.class.getClassLoader().getResourceAsStream("/"+image); //NOT FOUND
}else {
cmd = " ? ";
}
System.out.println("With "+cmd+", stream loaded: "+(is != null));
}
}
Run with:
java -cp resLoader.jar image.ImageLoader test4
Hope this class can help in understanding the different behaviour.
The project runs fine when I click play in Eclipse but after I created the runnable JAR file, The ImageIcon for the button is gone.
The images are stored within the src folder, uder a subfolder images.
I created the image icon as
Icon playIcon = (Icon) new ImageIcon("src/images/play.png");
Although I am using a relative path, the button does not display images, How do I get the images even in the JAR file?
Update after Nikolay Kuznetsov's answer
I ended up creating a very unstructured monolithic code for screen recorder and now it is slightly difficult to implement what he said.
I was wondering if there is a way like creating a class or interface that will contain all these resources.
For example:
public class embeddedResources {
public static Icon blackCursor;
public static Icon whiteCursor;
...
...
}
Then all I have to do is import these statics and in my main ScreenRecorder class,
this.blackCursor = embeddedResources.blackCorsor;
I am using this method to read image into BufferedImage where IconManager is class where it is defined.
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
I had the same problem.
Try to make you JAR file and add your images to an extern folder.
So you have a folder "Game" in this folder are the folder for your images called "images" or so and your jar file.
If you now edit you folder path to "../images/play.png" it should work.
I need it to run without having the files exported to the computer.
At the moment, my code for storing the images is:
ImageIcon icon = new ImageIcon("images\\images2.gif");
It can't just be an image since I'm adding it to a JLabel.
When I jar the entire program, it stores the image files in the jar.
When I go to run the actual problem, there are no images.
Again, I can't just leave the .jar in a folder with the images already. It has to work on a separate computer, by itself.
You'll want to get the image via the system class loader:
URL url = ClassLoader.getSystemClassLoader().getResource("images/images2.gif");
Icon icon = new ImageIcon(url)
images is at the root of the classpath.
Note that the Java runtime will translate the separator (/) to the OS specific separator (\ for Windows).
You need to access those files through class-loader... Something like this:
InputStream is = this.getClass().getClassloader().getResourceAsStream("images/image.ico");
HTH
UPD: note, that this will work both with JARed package and with plain directory structure.
The basic issue is that the File class only knows how to work with what the underlying operating system consider a file, and a whole one.
A jar file is essentially a zip file with some extra information so you cannot use File's with that. Instead Java provides the "resource" concept which roughly translates to "a chunk of bytes or characters which we don't care where is, as long as we have them when we need them". You can ask the class loader for any resource in the class path - which is what you want here - or access it through an URL.
Try this:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("images/images2.gif"));
if that doesn't work, replace this.getClass().getClassloader() with MyClass.class where MyClass is the name of your class.
I remember having to edit this slightly to make it work in Eclipse, but when you deploy it, it works like a charm.
Edit: To make it work in Eclipse, you may need to change it to:
ImageIcon icon = new ImageIcon(this.getClass().getClassloader().getResource("bin/images/images2.gif"));
If that doesn't work, do the standard, replace this.getClass().getClassloader() with MyClass.class. If it still doesn't work, try replacing "bin" with "src". Try jar'ing it with the first way and see what happens.
Here is a convenient utility class that can be used for loading image resources. The log4j logger can be removed of changed to whatever is more appropriate.
public class ResourceLoader {
private static final Logger logger = Logger.getLogger(ResourceLoader.class);
public static Image getImage(final String pathAndFileName) {
try {
return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static ImageIcon getIcon(final String pathAndFileName) {
try {
return new ImageIcon(getImage(pathAndFileName));
} catch (final Exception e) {
logger.error(e.getMessage());
return null;
}
}
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
}
I suppose images2.gif is inside the package images
URL imageurl = getClass().getResource("/images/images2.gif");
Image myPicture = Toolkit.getDefaultToolkit().getImage(imageurl);
JLabel piclabel = new JLabel(new ImageIcon( myPicture ));
piclabel.setBounds(0,0,myPicture.getWidth(null),myPicture.getHeight(null));
If your images are located this way.
Then this should do the job.
private String imageLocation "/images/images2.png";
private ImageIcon getImageIconFromJar(String imageLocation)
{
try
{
BufferedImage bi = ImageIO.read(this.getClass().getResource(imageLocation));
ImageIcon ic = new ImageIcon(bi);
return ic;
} catch (IOException e)
{
System.out.println("Error: "+e);
}
return null;
}