[英]How can I specify the icon's path if icon doesn't have a specified address?
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);
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.在这段代码中,图片的地址是特定的,但是如果图片和 jar 文件在 zip 文件中,图标将在 jar 文件中,我该怎么办。 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.如果您尝试加载 JAR 中的图像,这是解决此问题的最简单方法。 This will also work if your jar is executed from within a zip archive.
如果您的 jar 从 zip 存档中执行,这也将起作用。
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.其中
MyClass
是您从中调用此代码的 class 的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.