Java - ImageIcon 不会显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2422160/
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-29 21:04:26  来源:igfitidea点击:

Java - ImageIcon won't show image

java

提问by ShrimpCrackers

searchIcon = new ImageIcon( "searchIcon.png" );

searchIconLabel = new JLabel();
searchIconLabel.setIcon(searchIcon);

....

searchHorizontalPanel.add( searchIconLabel );

I'm trying to load the icon but it won't show up. The jpanel is within a boxlayout. I don't know if that messes things up. It's strange because I can add pretty much anything else except icon images. I went through the debugger and searchIcon is showing the width and height to be -1. Does this mean the image is not being loaded?

我正在尝试加载图标,但它不会显示。jpanel 位于 boxlayout 中。我不知道这是否把事情搞砸了。这很奇怪,因为除了图标图像之外,我几乎可以添加任何其他内容。我通过调试器,searchIcon 显示宽度和高度为 -1。这是否意味着没有加载图像?

回答by objects

Your image file needs to be in the same directory as you are running the application from.

您的图像文件需要与您运行应用程序的目录位于同一目录中。

If its actually in the same directory as the class making the call then you can use:

如果它实际上与进行调用的类位于同一目录中,那么您可以使用:

searchIcon = new ImageIcon( getClass().getResource("searchIcon.png") );

If it is in some arbitrary location then you will need to specify the full path.

如果它位于某个任意位置,则您需要指定完整路径。

回答by camickr

I went through the debugger and searchIcon is showing the width and height to be -1. Does this mean the image is not being loaded?

我通过调试器,searchIcon 显示宽度和高度为 -1。这是否意味着没有加载图像?

Yes.

是的。

Read the JLabel API and you will find a link to the Swing tutorial on "How to Use Lables" which has a working example.

阅读 JLabel API,您将找到指向“如何使用标签”的 Swing 教程的链接,其中有一个工作示例。

You will also find a section on "How to Use Icons" which shows all the different ways to specify the icon location correctly.

您还将找到有关“如何使用图标”的部分,其中显示了正确指定图标位置的所有不同方法。