Skip to content
Advertisement

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 height to be -1. Does this mean the image is not being loaded?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement