3

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?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
MattL922
  • 621
  • 2
  • 7
  • 12
  • 5
    Do not use the null layout manager. – mre Jan 16 '12 at 17:39
  • @mre Thats the only reason? All the other layouts seem so unintuitive. Absolute layout is so much easier to lay things out in the gui. There is no way to make this work with absolute layout? – MattL922 Jan 16 '12 at 17:42
  • 3
    @MattL922: It's not the reason. It's just a very very bad practice to use the null layout manager. Your GUI will look like crap on another machine with different settings. Learn to use layout managers. It's the only way to design good-looking GUIs. – JB Nizet Jan 16 '12 at 17:47
  • All of these answers are probably correct but the problem ended up being my use of the null layout. – MattL922 Jan 16 '12 at 18:13

5 Answers5

4

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That actually ended up printing out the same directory I have the image file in, but I'll still try using Class.getResource – MattL922 Jan 16 '12 at 17:48
  • 3
    If the directory is the right one, and the file is named bg.png, then it's probably caused by your usage of the null layout, or by the fact that the image is so small or transparent that you don't see it. Remove `setLayout(null)` from your code, and call `pack()` at the end of the constructor. – JB Nizet Jan 16 '12 at 18:05
  • Ok so I guess it wasn't actually a problem with my code it was just that I was using absolute layout. Can anyone point me to some good resources for learning the other layouts and why absolute is not a good choice? – MattL922 Jan 16 '12 at 18:08
  • It was a problem with your code, because loading an image from the current directory is very rarely a good idea, and because using the null layout is almost never a good idea. The swing tutorial has everything you need: http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html – JB Nizet Jan 16 '12 at 18:18
  • +1, for specifying that the issue is because of setLayout(null), then you have to manually set the bounds for the JLabel. Regards – nIcE cOw Jan 16 '12 at 18:18
3

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

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;
    }
}
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
2

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

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
0

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.

stealthyninja
  • 10,343
  • 11
  • 51
  • 59
YiFan Wu
  • 123
  • 5