简体   繁体   English

Java - ImageIcon 不显示图像

[英]Java - ImageIcon won't show image

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. jpanel 在 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.我通过了调试器,searchIcon 显示宽度和高度为 -1。 Does this mean the image is not being loaded?这是否意味着未加载图像?

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. 如果它位于任意位置,则需要指定完整路径。

I went through the debugger and searchIcon is showing the width and height to be -1. 我通过调试器,searchIcon显示宽度和高度为-1。 Does this mean the image is not being loaded? 这是否意味着未加载图像?

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. 您还将找到“如何使用图标”一节,其中显示了正确指定图标位置的所有不同方法。

If you haven't imported java.awt.BufferedImage then the computer would not be able to allow access to Java to load the images.如果您还没有导入 java.awt.BufferedImage 那么计算机将无法允许访问 Java 来加载图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM