Home > Back-end >  How can I specify the icon's path if icon doesn't have a specified address?
How can I specify the icon's path if icon doesn't have a specified address?

Time:01-28

I have a frame and want to set an icon for it. I use this code : JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(null); f.setTitle("add icon example"); f.setBounds(200,200,200,200); Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png"); f.setIconImage(icon); f.setVisible(true); In this code , the address of image is specific , but what can I do if image and jar file are in a zip file and icon will be with jar file. I think I can write a code to unzip the file and then save the image in a specified address and then use it. But , please anyone help me to do it. Thanks.

CodePudding user response:

If you're trying to load an image that's within a JAR, this is the most simple approach to this problem. This will also work if your jar is executed from within a zip archive.

        BufferedImage image = ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("image_name.png"));

Where MyClass is the name of the class you're calling this code from.

CodePudding user response:

The answer is something like

BufferedImage im = ImageIO.read(myClass.getResourceAsString("iconName"));
  • Related