Cannot retrieve image by relative path - java

I am trying to retrieve a picture by relative path but it always returns a java.lang.NullPointerException no matter what path combination I try
private final Icon cardBack = new ImageIcon(getClass().getResource(
"src/main/resources/Images/cardIcons/cardBack.png"));
https://pastebin.com/sDjP87p3

I've ran into this error before. You have to add the " / " before your path.

I believe the NPE is being thrown from the ImageIcon constructor as getResource is returning null.
Try the following:
private final Icon cardBack = new ImageIcon(getClass().getClassLoader().getResource("src/main/resources/Images/cardIcons/cardBack.png"));
Or:
private final Icon cardBack = new ImageIcon(ClassLoader.getSystemResource("src/main/resources/Images/cardIcons/cardBack.png"));

private final Icon cardBack = new ImageIcon(getClass().getResource("/Images/cardIcons/cardBack.png"));
Worked after I remade the app into a normal java project. Apparently the problem was caused by Maven, cause yet unknown.

Related

FileDialog generating GtkDialog mapped without a transient parent. This is discouraged

My java code is generating the following message when I create a open FileDialog and make it visible. I have checked the code against code examples and I can't find anything wrong. And I am passing in the parent frame reference into the constructor. This is the code example:
public void open() {
if (openAreYouSure()) {
MyFilenameFilter filter = new MyFilenameFilter(Editor.JAWS_FILE_TYPE);
FileDialog d = new FileDialog(frame, "Open", FileDialog.LOAD);
d.setFilenameFilter(filter);
d.setBackground(lightSteelBlue3);
if (!mostRecentDir.equals(""))
d.setDirectory(mostRecentDir);
d.setVisible(true);
String path = d.getDirectory();
String file = d.getFile();
if (path != null && file != null) {
Editor.logger.info("opened file: " + path + file);
newSession();
mostRecentDir = path;
openFile(path + file);
}
}
}
This comes out when the d.setVisible(true); is called.
Gtk-Message: 12:10:44.979: GtkDialog mapped without a transient parent. This is discouraged.
This is the version of java I am using on centos 7.
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.275.b01-0.el7_9.x86_64/jre/bin/java
All the write ups on this type of messages say its caused because you didn't pass in the parent into the dialog you are created, but I am in the constructor. This is happening for all pop dialog my application is creating.
Does anyone have any idea how to suppress or fix this problem? I am not seeing any java bug report on this, but I assume there is somewhere.

File exist but glide does not show anything

This is my code:
String mmimg = Environment
.getExternalStorageDirectory().toString()+arrPictures.get(0).getPath();
Log.e("mmimg",mmimg); ///storage/emulated/0/productss/Montearci_products/Bracelets/airplane/Brac - 020.jpg
File mfile = new File(mmimg);
Uri muri = Uri.fromFile(mfile);
if(!mfile.exists()){
Log.e("oops","oooops"); //it does't show
}
Glide.with(getApplicationContext())
.load(muri)
.fitCenter()
.into(mimg);
but my imageView doesn't not show anything.
please test this code and reply if solved your problem :
put this instead of the first line :
String mmimg = Environment
.getExternalStorageDirectory().getPath()+arrPictures.get(0).getPath();
and I think it is better that you say what kind of data you have in the arrayList.

Substitute ImageIcon with ImageIO to load images

I'm making a java game using Eclipse. When I export to a runnable jar and try to run the game on different computer the images aren't visible. After checking the web and stack overflow for similar problems I think it has something to do with my using ImageIcon instead of ImageIO. However, I'm not sure how to change my code so that I'm uploading the images with ImageIO instead of ImageIcon.
Here is the method that uses ImageIcon to load the images
void loadImage() {
ImageIcon earth_image_icon = new ImageIcon("earth2.png");
earth = earth_image_icon.getImage();
ImageIcon sun_image_icon = new ImageIcon("sun2.png");
sun = sun_image_icon.getImage();
ImageIcon asteroid_image_icon = new ImageIcon("asteroid.png");
asteroid = asteroid_image_icon.getImage();
ImageIcon bg_image_icon = new ImageIcon("bg_pr.png");
background = bg_image_icon.getImage();
ImageIcon shipA_image_icon = new ImageIcon("ship_alpha.png");
ship_on_asteroid = shipA_image_icon.getImage();
ImageIcon ship_image_icon = new ImageIcon("ship_beta.png");
ship_no_thrust = ship_image_icon.getImage();
ImageIcon shipL_image_icon = new ImageIcon("ship_betaL.png");
ship_left_thrust = shipL_image_icon.getImage();
ImageIcon shipR_image_icon = new ImageIcon("ship_betaR.png");
ship_right_thrust = shipR_image_icon.getImage();
ImageIcon shipU_image_icon = new ImageIcon("ship_betaU.png");
ship_up_thrust = shipU_image_icon.getImage();
ImageIcon shipD_image_icon = new ImageIcon("ship_betaD.png");
ship_down_thrust = shipD_image_icon.getImage();
ImageIcon leftarrow_image_icon = new ImageIcon("leftarrow.png");
leftarrow = leftarrow_image_icon.getImage();
ImageIcon rightarrow_image_icon = new ImageIcon("rightarrow.png");
rightarrow = rightarrow_image_icon.getImage();
ImageIcon downarrow_image_icon = new ImageIcon("downarrow.png");
downarrow = downarrow_image_icon.getImage();
ImageIcon uparrow_image_icon = new ImageIcon("uparrow.png");
uparrow = uparrow_image_icon.getImage();
}
And here is one of the methods that draws the image onto the JPanel as an example
void drawEarth(Graphics g) {
g.drawImage(earth, earth_x_coordinate, earth_y_coordinate, this);
Toolkit.getDefaultToolkit().sync();
}
How do I convert to using ImageIO? I've checked out the Oracle documentation but I'm getting lost trying to sort it out and I'm very new to programming and java at that.
Update It's been suggested that this might be the solution my particular problem but I tried the answers given on this post and they didn't work for my case.
You will need to include the image resources in your compiled jar. An easy way of doing this if you are using an IDE like eclipse is to create a res or img folder and put your files in there. (Use the methods given here.)
In that case, you probably won't need to use ImageIO. However, if you still want to use ImageIO (which is recommended because of its wider support for formats and better exception handling, as mentioned in the comments), you can do the following:
Icon foo = new ImageIcon(ImageIO.read(getClass().getResource("foo.png")))
I created a new project in eclipse and copied the class files into the new projects src folder. I then made a resource folder, added it to the build path, created an images package in that resource folder and copied the images into that images package. For some reason this all worked. Thanks everyone for your help

Uncaught error fetching image in exported jar

i have an application that loads an image to create a button with an icon in it. When started from the IDE, it works just fine, but when started from an exported jar file, it gives an image fetching error.
Location of images :
+Project
-Source Packages
-Tools
-start.jpg
The code used :
static final String STARTIMAGE = "/Tools/start.JPG";
public static JButton createStartButton() {
Image img = Toolkit.getDefaultToolkit().getImage(GUITools.class.getResource(STARTIMAGE));
JButton b = new JButton("",new ImageIcon(img));
b.setPreferredSize(smallButton);
b.setMaximumSize(smallButton);
b.setMinimumSize(smallButton);
return b;
Now, the weirdest thing is that in another screen, a button is created in the exact same way, and this one works just fine...
Code:
static final String PREVIOUSIMAGE = "/Tools/previous.gif";
public JButton createPreviousButton(){
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(PREVIOUSIMAGE));
JButton b = new JButton("Previous",new ImageIcon(img));
b.setPreferredSize(dimensionButton);
b.setMaximumSize(dimensionButton);
b.setMinimumSize(dimensionButton);
return b;
}
The only difference is that one is static, but even if make it non-static like the other one, it still won't work.
I tried everything I found on this forum and other sites, including this good topic :
How to bundle images in jar file
(The generated url at the end of the topic is just 'null')
Nothing seems to work... Please help!
Thanks!
When started from the IDE, it works just fine, but when started from an exported jar file, it gives an image fetching error.
Image img = Toolkit.getDefaultToolkit().getImage(getClass().getResource(PREVIOUSIMAGE));
This approach above is incorrect, use this instead:
private static BufferedImage readBufferedImage (String imagePath) {
try {
InputStream is = YourClassName.class.getClassLoader().getResourceAsStream(imagePath);
BufferedImage bimage = ImageIO.read(is);
is.close();
return bimage;
} catch (Exception e) {
return null;
}
}
And better load all images at application startup and then use them.
It seems to me that your images are inside a package so the actual link might be "package.name/Tools/start.jpg" or something else when its compiled so the image should be moved.
Instead of having it inside of a package like:
+Project
-Source Packages
-Tools
-start.jpg
Do something like this instead.
+Project Folder
-Source Packages/
-Tools/
-start.jpg

Changing JRadioButton Icon on Windows 7

I created a method which changes the icon of all jradiobuttons from a buttongroup:
public void setRadioButtonIcons(final ButtonGroup gruppe){
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
This works fine under Ubuntu with Java 1.6.0_16.
When I use the methode under windows 7 with java 1.6.0_18, the icons do not apear. They are simply missing. The programm does not throw a Nullpointer... it finds the icons, but does not display them. Any ideas? It seems somewhat hard to believe that I can not use such a simple functionality under windows.
I tried it with gif and jpg. I also put the images inside the jar and tried to load them from the filesystem -> same result.
Edit: In this configuration, the files are loaded from the jar.
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
You shouldn't be calling getPath() there, should just be:
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
It won't be able to access a resource in a jar by path and an ImageIcon can load an image using a URL just fine.
If you still are not seeing your icons then it may be that the L&F you are using does not use those icons and instead uses its own. Perhaps try testing the code with a different L&F.
Try removing the calls to getPath(), like this:
public void setRadioButtonIcons(final ButtonGroup gruppe) {
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
The problem is that URL.getPath() gives you a string URL, which isn't necessarily a valid string filename of the sort that the ImageIcon string constructor expects. Fortunately, ImageIcon has another constructor that understands URL objects, and so there's no need to call getPath().

Categories

Resources