Search code examples
javaswinguser-interfaceembedded-resourceimageicon

Icon path for JFrame


I need image icon on jframe but I dont want to give path. I am using this

jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\ABC\\Desktop\\folder name\\1.jpg"));

Because every system has different path and this is the reason I can not compile this on other system(computer). I need some way so I can set image icon through file name only. And the image is in src folder.


Solution

  • Read the Image as an embedded resource. The new images folder shown here just needs to be available on the classpath

    public class ImageApp {
    
        public static void main(String[] args)  {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    Image image = null;
                    try {
                      image = ImageIO.read(getClass().getResource("/images/1.png"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Image App");
                    frame.add(new JLabel(new ImageIcon(image)));
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    }