I\'ve gone through every post I could find on this site and the Java tutorials and I still can\'t figure out why my code isn\'t working. Even when I copy/paste other peoples\'
What you're doing wrong is that when you call new ImageIcon("bg.png")
, you try loading the bg.png
file from the current directory. The current directory is the directory from which java
is executed. And the current directory is probably not the directory you believe when you execute java
from your IDE.
Use the following code to display the current directory:
File dir1 = new File (".");
System.out.println("current directory: " + dir1.getAbsolutePath());
You should probably load the png file from the classpath, using Class.getResource("/images/bg.png")
. Create an images
folder in your source directory, and put the file in this directory. Your IDE will copy it to the target folder, along with the .class
files. If you're not using an IDE, then you'll have to copy it yourself.
EDIT:
After more investigations, it appeared that the root cause of the problem was the use of the null layout. The above still stands, though, because loading a file from the current directory is not a good idea.