Reputation: 173
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.
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.
Upvotes: 0
Views: 2630
Reputation: 6802
change
bf = new ImageIcon("car.png");
to
URL url = Main.class.getResource("car.png");
bf = new ImageIcon(url);
Upvotes: 1
Reputation: 10606
Check that if car.png
is under the bin
directory in the filesystem (it is filtered out in Eclipse, so do it in a file explorer).
Btw I would suggest using something like ImageIO.read(Main.class.getResource("/car.png"))
. The reason is the following: later on you will probably package your app (into a Jar file for example). Now if you do it this way, Java is able to locate the image even if it is executed as a Jar or from
Upvotes: 1