Search code examples
javaswingjbuttonembedded-resourceimageicon

Java JButton Image


Hey so I've moved my images to the correct work space folder(src) but i keep getting this error message.....

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at GUI.<init>(GUI.java:20)
    at main.main(main.java:4)

This is the code

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;

public class GUI extends JFrame {
    private JButton reg;
    private JButton custom;
    public GUI(){
        super("Welcome");
        setLayout(new FlowLayout());
        reg = new JButton("reg button");
        add(reg);

        Icon b = new ImageIcon(getClass().getResource("b.png"));
        Icon a = new ImageIcon(getClass().getResource("a.png"));
        custom = new JButton("Custom", b);
        custom.setRolloverIcon(a);
        add(custom);

        thehandler handle = new thehandler();
        reg.addActionListener(handle);
        custom.addActionListener(handle);

    }

    private class thehandler implements ActionListener{
        public void actionPerformed(ActionEvent event){
            JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
        }
    }

}


-----------------------

import javax.swing.JFrame;
public class main {
public static void main(String agrs[]){
    GUI page = new GUI();
    page.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    page.setSize(300,200);
    page.setVisible(true);
}
}

Solution

  • you must put your image in the folder that contains src to use directly, not in src itself.