Reputation: 2019
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.
Upvotes: 0
Views: 599
Reputation: 2391
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()
.
Upvotes: 2
Reputation: 8677
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.
Upvotes: 2