JButton Image Icon not displaying .png file

David picture David · Jul 19, 2013 · Viewed 8k times · Source

I've been looking everywhere for a solution to this and read some similar posts related to this problem but none of them worked for me.

I'm trying to display the image "b.png" on the JButton and when i roll over the button the icon changes.

package GUI_JButton;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Gui extends JFrame {

    private JButton reg;
    private JButton custom;

    public Gui() {
        super("Title goes here");
        setLayout(new FlowLayout());

        reg = new JButton("reg button"); // create reg button
        add(reg); // add reg button to JFrame

        // initialize images
        Icon b = new ImageIcon(getClass().getResource("images/imageA.png"));
        Icon x = new ImageIcon(getClass().getResource("images/imageB.png"));

        custom = new JButton("custom button", b); // create custom button
        custom.setRolloverIcon(x);
        add(custom); // add button to JFrame

        HandlerClass handler = new HandlerClass();
        reg.addActionListener(handler);
        custom.addActionListener(handler);

    }

    private class HandlerClass implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(null,
                    String.format("%s", event.getActionCommand()));

        }

    }

}

The images are in a folder named images which is in the src folder alongside the Gui.java file and the TESTMain.java file.

The error i'm getting is a null pointer exception from Main. I have tried

Icon b = new ImageIcon("images/imageA.png"); 

This compiles but the image is not displayed. I have also tried

custom = new JButton("custom", new ImageIcon("images/imageA.png"));

And

custom = new JButton("custom", new ImageIcon(getClass().getResource("images/imageA.png"));

I know that getClass().getResource() is prefferred as the images need to be compiled with the jar.

Any ideas on getting my images to display?

Answer

Luke picture Luke · Jul 19, 2013

Your images folder needs to be in the same folder as your compiled .class files, instead of in src with your .java files.