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);
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.
The answer is something like
BufferedImage im = ImageIO.read(myClass.getResourceAsString("iconName"));
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.
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.