java 在面板中设置图像图标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10266803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Image Icon in Panel
提问by sohel14_cse_ju
I want to set an image icon in a panel.I am trying to do like this ;
我想在面板中设置一个图像图标。我正在尝试这样做;
JLabel label = new JLabel(new ImageIcon("logo.jpg"))
panelHeader.add(label);
add(panelHeader);
But the image is not showing.Any suggestion what i am doing wrong?
但图像没有显示。任何建议我做错了什么?
回答by miqbal
The new ImageIcon()
constructor just creates an uninitialized image icon. You must invoke the createImageIcon()
method that returns ImageIcon
source to assign to your also created ImageIcon
object.
该new ImageIcon()
构造仅仅是创建一个未初始化的图像图标。您必须调用createImageIcon()
返回ImageIcon
源的方法以分配给您也创建的ImageIcon
对象。
ImageIcon icon = createImageIcon("logo.jpg", "my logo");
JLabel label = new JLabel(icon);
回答by Andrew Thompson
new ImageIcon("logo.jpg")
The String
based constructor for an ImageIcon
presumes the string represents a file path. Since this is an image that is added to a panel, by run-time, it will likely be inside a Jar and not accessible as a File
. For an embedded application resource, the only viable access is by URL
. The URL might be obtained from something like:
的String
基础构造函数ImageIcon
假定字符串表示文件路径。由于这是一个添加到面板的图像,在运行时,它很可能位于 Jar 中,不能作为File
. 对于嵌入式应用程序资源,唯一可行的访问是通过URL
. URL 可能是从以下内容中获取的:
URL logoUrl = this.getClass().getResource("/logo.jpg");
Note the leading /
. That tells the JRE to search for the resource on a path relative to the root of the class-path, as opposed to a path relative to the package of the class that loads it.
注意领先的/
. 这告诉 JRE 在相对于类路径根的路径上搜索资源,而不是相对于加载它的类的包的路径。