java – 如何访问JAR文件中的资源?
发布时间:2020-12-15 00:04:27 所属栏目:Java 来源:网络整理
导读:我有一个带有工具栏的 Java项目,工具栏上有图标.这些图标存储在名为resources /的文件夹中,例如路径可能是“resources / icon1.png”.这个文件夹位于我的src目录中,所以当它被编译时,文件夹被复制到bin / 我正在使用以下代码来访问资源. protected AbstractB
我有一个带有工具栏的
Java项目,工具栏上有图标.这些图标存储在名为resources /的文件夹中,例如路径可能是“resources / icon1.png”.这个文件夹位于我的src目录中,所以当它被编译时,文件夹被复制到bin /
我正在使用以下代码来访问资源. protected AbstractButton makeToolbarButton(String imageName,String actionCommand,String toolTipText,String altText,boolean toggleButton) { String imgLocation = imageName; InputStream imageStream = getClass().getResourceAsStream(imgLocation); AbstractButton button; if (toggleButton) button = new JToggleButton(); else button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(listenerClass); if (imageStream != null) { // image found try { byte abyte0[] = new byte[imageStream.available()]; imageStream.read(abyte0); (button).setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(abyte0))); } catch (IOException e) { e.printStackTrace(); } finally { try { imageStream.close(); } catch (IOException e) { e.printStackTrace(); } } } else { // no image found (button).setText(altText); System.err.println("Resource not found: " + imgLocation); } return button; } (imageName将是“resources / icon1.png”等).这在Eclipse中运行时工作正常.但是,当我从Eclipse导出可运行的JAR时,找不到图标. 我打开了JAR文件,资源文件夹在那里.我已经尝试了所有的东西,移动文件夹,更改JAR文件等,但我无法获得显示的图标. 有谁知道我做错了什么? (作为一个侧面的问题,有没有可以使用JAR文件的文件监视器?当路径问题出现时,通常只需打开FileMon即可看到发生了什么,但是在这种情况下它只是显示为访问JAR文件) 谢谢. 解决方法
要从JAR资源加载映像,请使用以下代码:
Toolkit tk = Toolkit.getDefaultToolkit(); URL url = getClass().getResource("path/to/img.png"); Image img = tk.createImage(url); tk.prepareImage(img,-1,null); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |