简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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