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\'
You're looking for the image as a file. When you do that the searches are all done in a path relative to the user directory which you can get via
// code not tested
System.out.println(System.getProperty("user.dir"));
So you will likely have to adjust your image's path to get it as a file. The other option is to get it as a resource as noted by Siva Charan in which case the path is relative to the location of your class files.
Oh and once you study and use the layout managers, they become intuitive, and creating and especially maintaing your GUI's become much easier.
You might need to debug it and check if the image file is loaded correctly. And then you need to check if the JLabel Component gets its size because adding the image to the JLabel wouldn't expand the JLabel.
First you should try to see the image handler has its width and height.
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.
Just simply put your bg.png, alongside your gui.class file. That will do, if you write this code
private ImageIcon getImage(String path)
{
URL url = getClass().getResource(path);
System.out.println(url);
if (url != null)
return (new ImageIcon(url));
return null;
}
More information can be found on Access to Resources
Here path = "bg.png"; or if it's inside some folder than path = "someFolder/bg.png"; So you be writing something like this :
JLabel lblNewLabel = new JLabel(getImage("bg.png"));
lblNewLabel.setBounds(30, 30, 100, 100);
Hope that might help.
Regards
Try this way:-
ImageIcon icon = createImageIcon("bg.png", "image description");
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file:" +path);
return null;
}
}