How to use getClass().getResource() method

前端 未结 3 1544
自闭症患者
自闭症患者 2020-12-06 07:30

When I create ImageIcon class objects I use the following code:

iconX = new ImageIcon (getClass().getResource(\"imageX.png\"))
3条回答
  •  感情败类
    2020-12-06 07:34

    If the image is internal (you want a location relative to your project, or perhaps packaged into your jar), do what mad programmer said:

    iconX = new ImageIcon(getClass().getResource("/path/imageX.png"))
    

    The path is relative, so path/ will be a folder in the same folder as your project (or packaged into your jar).

    If you want an external image, simply hand ImageIcon constructor the path (ex. "C:/.../file.png"). This isn't recommended though, as it's better to use it as a resource.

    For more info on the ImageIcon constructor, see here. for more info on loading class resources, see here (Javadoc links)

提交回复
热议问题