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’ code, it still doesn’t work.
I’ve made a dummy program just to test this out and the code looks like so:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class gui extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui frame = new gui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public gui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 900, 700);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel(new ImageIcon("bg.png"));
contentPane.add(lblNewLabel);
}
}
The background image I’m trying to display, bg.png, is located in the project’s root folder. I tried multiple formats for the path string with no success. What am I doing wrong?
What you’re doing wrong is that when you call
new ImageIcon("bg.png"), you try loading thebg.pngfile from the current directory. The current directory is the directory from whichjavais executed. And the current directory is probably not the directory you believe when you executejavafrom your IDE.Use the following code to display the current directory:
You should probably load the png file from the classpath, using
Class.getResource("/images/bg.png"). Create animagesfolder in your source directory, and put the file in this directory. Your IDE will copy it to the target folder, along with the.classfiles. 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.