Search code examples
javaimageswingembedded-resourceimageicon

Java Image not showing up in Swing


I've made a JLabel with the Icon being an ImageIcon and it doesn't seem to be recognized.

When I add it to the project root it shows up in my IDE but it doesn't get added to the jar file when building.

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class create {
    Random rand = new Random();
    int x = Toolkit.getDefaultToolkit().getScreenSize().width;
    int y = Toolkit.getDefaultToolkit().getScreenSize().height;
    public void CreateJFrame() {
        JFrame j = new JFrame("Test");
        j.setLocation(rand.nextInt(x), rand.nextInt(y));
        j.setPreferredSize(new Dimension(rand.nextInt(x), rand.nextInt(y)));
        j.setResizable(false);
        j.setLayout(new FlowLayout());
        j.pack();

        ImageIcon img = new ImageIcon("image.png"); // this file is in the resources folder and it is present in the jar file
        JLabel imgLabel = new JLabel(" ");
        imgLabel.setIcon(img);
        j.getContentPane().add(imgLabel);

        j.setVisible(true);

    }
}

Solution

  • Use this constructor: new ImageIcon(ImageIO.read(create.class.getResourceAsStream("image.png"))). You should use it because you cannot get files from the jar file, but you should use InputStream to read (and not write) from files in your jar file. In addition to the this, make sure your image are in the jar file main directory and not in sub directories.