0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Madan
  • 3
  • 2

2 Answers2

4

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);
            }
        });
    }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
-1

You can use relative path: for example, if icon is in program working directory (the same directory as program) you can just use "1.jpg", if in folder - "folderName/1.jpg".

Mac70
  • 320
  • 5
  • 15
  • *"You can use relative path"* 1) Very fragile. It presumes the current directory is that of the running Jar, which is not necessarily true of a desktop app. run from an executable Jar, and *never* true of a desktop app. run using JWS. 2) This icon is likely to become an embedded-resource by time of deployment, and will not be accessible as a `File` in any case. – Andrew Thompson Sep 04 '13 at 14:15