开发者

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. 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 开发者_StackOverflow社区height to be -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. 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜