Java - ImageIcon won't show image

后端 未结 2 431
情歌与酒
情歌与酒 2021-01-26 09:30
searchIcon = new ImageIcon( \"searchIcon.png\" );

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

....

searchHorizontalPanel.add( searchIconLabel         


        
相关标签:
2条回答
  • 2021-01-26 09:46

    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.

    0 讨论(0)
  • 2021-01-26 10:08

    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.

    0 讨论(0)
提交回复
热议问题