Reputation: 21
So when i'm tried to put an icon to my button with createIcon()
method that i declared inside of the button's class, it works fine.
BUT,
when i try to put the method in another class (say Utils.java
), so that i don't need to re-declare the method in the class where the object needs icon, i get this message.
Unable to load image: /images/Save16.gif
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
*there's more message if needed
this is the button's class with createIcon() method inside
public class Toolbar extends JToolBar implements ActionListener{
private final JButton saveBtn;
public Toolbar() {
saveBtn = new JButton();
saveBtn.setIcon(createIcon("/images/Save16.gif"));
saveBtn.setToolTipText("Save");
saveBtn.addActionListener(this);
add(saveBtn);
}
private ImageIcon createIcon(String path) {
URL url = getClass().getResource(path);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
ImageIcon icon = new ImageIcon(url);
return icon;
}
}
this is the createIcon() method that i'm trying to declare in another class
public class Utils {
public static ImageIcon createIcon(String path) {
URL url = System.class.getResource(path);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
ImageIcon icon = new ImageIcon(url);
return icon;
}
}
which changed the setIcon()
method into:
saveBtn.setIcon(Utils.createIcon("/images/Save16.gif"));
from what i analyzed in the message the problem is might be the url
which can't get the path
from my button's class, i've tried several alternatives but it's still didn't work. how should i properly set this up? thanks
Upvotes: 0
Views: 4137
Reputation: 324098
This works:
URL url = getClass().getResource(path);
because you get the class of your Toolbar class, which is where all your other classes/files are located.
This doesn't work:
URL url = System.class.getResource(path);
because the "System" class is found in the JDK not with your application classes.
I would guess you could try:
URL url = Utils.class.getResource(path);
Upvotes: 1