简体   繁体   中英

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.

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);
            }
        });
    }
}

您可以使用相对路径:例如,如果图标位于程序工作目录(与程序相同的目录)中,则可以仅使用“ 1.jpg”,如果位于文件夹“ folderName / 1.jpg”中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM