Search code examples
javaiconsjbutton

Can't locate ImageIcon in JButton


I am trying to assign a png type image to a JButton which is already created.

I've added a resource folder in the root folder of the project named images. I've tried to approach it with many ways as similar questions already exists but I can't seem to figure it out...

ImageIcon ico = new ImageIcon("/images/water.png");
bSquares[pos][line].setIcon(ico);

I've also tried many other paths like The source: ImageIcon ico = new ImageIcon("/TelikoDama/images/water.png");

I think it's the paths fault, or maybe my eclipse does not locate it? I don't know.

This is the NPE Im getting:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at cheeckers.gameUI.initializeGui(gameUI.java:112)
    at cheeckers.gameUI.<init>(gameUI.java:33)
    at cheeckers.gameUI$1.run(gameUI.java:226)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:745)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:715)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

EDIT I found a workaround, I've manually set the path of the folder in the .classpath:

<classpathentry kind="src" path="/src/images"/>

AND acessed the image like this:

Image ico = new ImageIcon(this.getClass().getResource("/images/water.png")).getImage();
                        bSquares[pos][line].setIcon(new ImageIcon(ico));

Solution

  • You should probably use this code to get the image file for pretty much every components that you find in java UI:

    JButton button = new JButton();
    Image img= ImageIO.read(getClass().getResource("//images/water.png"));
    button.setIcon(new ImageIcon(img));