Search code examples
javaeclipseimageicon

Displaying an imageicon in eclipse doesn't work


So I've just written down some simple code that just displays an image in a JButton. What I have done is write the code:

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Main extends JFrame{

public static ImageIcon bf;
public static JPanel p;
public static JButton b;

public static void main (String args[]){
    Main main = new Main();

    bf = new ImageIcon("car.png");
    p = new JPanel();
    b = new JButton(bf);
    p.add(b);
    main.add(p);

    main.setVisible(true);
    main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
    main.setSize(600,700);


}

}

And I have copied a pic named car.png in the same folder with my class, but I can't seem to get it to work in elipse.

enter image description here

But when I run the same exact code in BlueJ it runs it without any known issues. Any help woul be greately apprecciated Thanks In advance.


Solution

  • change

    bf = new ImageIcon("car.png"); 
    

    to

        URL url = Main.class.getResource("car.png");
        bf = new ImageIcon(url);