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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:18:19  来源:igfitidea点击:

Set Image Icon in Panel

javaswing

提问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 ImageIconsource to assign to your also created ImageIconobject.

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 Stringbased constructor for an ImageIconpresumes 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 在相对于类路径根的路径上搜索资源,而不是相对于加载它的类的包的路径。

回答by trashgod

You've got two good answers on creating the ImageIcon. You should also look at the layout of the container to which you add the label. This exampleuses FlowLayout, the implicit default for JPanel.

在创建ImageIcon. 您还应该查看添加标签的容器的布局。此示例使用FlowLayout, 的隐式默认值JPanel