Search code examples
javaswingnullpointerexceptionembedded-resourceimageicon

Swing ImageIcon causing error and not making image appear


I am having a problem with my java project. I am trying to make a JFrame with a background image, but when I use javax.swing.ImageIcon to set the icon of the background JLabel it shows an exception error in the console when I run the program and the image doesn't work, only showing a blank JFrame. Here is my code:

@SuppressWarnings("serial")
public class MainUI extends JFrame {
    public static void main(String[] args) {
        new MainUI().build(); // Calls build method
    }
    private void build() {
        // Builds JFrame
        JFrame frame = new JFrame();
        JPanel base = new JPanel();
        JLabel background = new JLabel();
        frame.setVisible(true);
        frame.setTitle("Space Age");
        frame.setSize(640,480);
        frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        frame.setAutoRequestFocus(false);
        frame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        frame.setLocationRelativeTo(null);
        base.setSize(640,480);
        base.setAlignmentX(0.0F);
        base.setAlignmentY(0.0F);
        base.setBackground(new java.awt.Color(255,255,255));
        background.setSize(640,480);
        background.setAlignmentX(0.0F);
        background.setAlignmentY(0.0F);
        background.setIcon(new ImageIcon(getClass().getResource("spaceage.images.starfield.png")));
        frame.add(base);
        frame.add(background);
    }
}

This is what the error message looks like:

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at spaceage.src.MainUI.build(MainUI.java:36)
    at spaceage.src.MainUI.main(MainUI.java:15)

Can someone tell me what I did wrong and how to to make the image display properly? Thanks in advance, Santiago


Solution

  • I figured out what I did wrong. This:

    background.setIcon(new ImageIcon(getClass().getResource("spaceage.images.starfield.png")));
    

    needed to be changed to this:

    background.setIcon(new ImageIcon(getClass().getResource("/spaceage/images/starfield.png")));
    

    I got a NullPointerException because I entered the path to my image incorrectly, so getResource() couldn't find the image and returned null.