Java Swing JButton getResource 不能正常工作
此代码在 Windows XP 上运行正确。但在家里的 Windows 7 机器上我看不到图标,因为 getResource 返回 null。我已经尝试过绝对路径,但它也不起作用。我不知道该怎么办,我正在管理员模式下运行 Eclipse:
private static JButton createToolButton(String imgName, String altText, String toolTipText) {
String imagePath = IMG_URL + "/" + imgName;
URL imageUrl = SwingUtility.class.getResource(imagePath);
JButton button = new JButton();
button.setToolTipText(toolTipText);
if(imageUrl != null) //Image trouvé
button.setIcon(new ImageIcon(imageUrl, altText));
else
button.setText(altText);
return button;
}
This code runs correctly on windows XP. But at home on my Windows 7 machine I can't see the icons because getResource returns null. I've tried an absolute path and it's not working either. I don't know what to do, I'm running Eclipse in Admin mode:
private static JButton createToolButton(String imgName, String altText, String toolTipText) {
String imagePath = IMG_URL + "/" + imgName;
URL imageUrl = SwingUtility.class.getResource(imagePath);
JButton button = new JButton();
button.setToolTipText(toolTipText);
if(imageUrl != null) //Image trouvé
button.setIcon(new ImageIcon(imageUrl, altText));
else
button.setText(altText);
return button;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getResource()
方法首先会在父类加载器中搜索资源;如果父级为空,则搜索虚拟机内置的类加载器的路径。如果失败,此方法将调用 findResource(String) 来查找资源。因此,在所有这些之后,如果它返回 null,则问题出在imagepath
ergoIMG_URL
上。另请注意,如果找不到资源或调用者没有足够的权限来获取资源,它会返回 null。The
getResource()
method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invokefindResource(String)
to find the resource. So after all these, if it returns null, the problem is withimagepath
ergoIMG_URL
. Also note that it returns null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.这是我的解决方案,并不理想,但它有效。经过多次测试后,我只是觉得使用点符号向上进入当前目录并不能完全按照使用基本 java 实用程序的预期工作。最终只是获取了项目路径并将其分割到我想要的地方,尚未在其他机器上进行测试。
Here's my solution, not ideal but it works. After many tests I just feel like using the dot notation to go up and into the current directory not work exactly as expected using the basic java utilities. Ended up just getting the project path and splitting it where I wanted, hasn't been tested on other machines yet.