Problems with images when compiled

前端 未结 2 713
暗喜
暗喜 2020-12-21 23:37

I have been all over the internet trying to work out how to get an image icon displayed after compiling into a runnable jar. I discovered this problem way too late, I ran my

相关标签:
2条回答
  • 2020-12-21 23:57

    With your current directory setup, the images dir won't even get built into the jar. Try to extract it and you will most likely see that it's not in there.

    You can tell by the fact that it doesn't have the little package logo in the folder, as seen here with resources

    enter image description here

    The only default directory built into the classpath (/jar) is the src. We need to either put the resources into the src

    enter image description here

    or configure the build path to include the files that are in the resources. Once we do that, we will see the little package icon inside the folder icon. That's how we know the files are on the build path

    enter image description here


    CODE we would use:

    • First Image: Can't, it won't work (this your current predicament)

    • Second Image:

      ImageIcon icon = new ImageIcon(
               getClass().getResource("/resources/stackoverflow.png"));
      
    • Third Image:

      ImageIcon icon = new ImageIcon(
               getClass().getResource("/stackoverflow.png"));
      

    To configure the build path to use the third option, follow the instructions in Example 2 in this answer

    0 讨论(0)
  • 2020-12-21 23:59

    As from your screenshot, the image exists in a folder called "images". Put it in a folder inside your classpath: src/images/success.jpg and call:

    ImageIcon a = new ImageIcon(getClass().getResource("/images/success.jpg")); 
    
    0 讨论(0)
提交回复
热议问题