intellij java desktop application how to use resources

Think_Twice :

I am busy with a java desktop application in intellij. I am struggling to get a image to display in a JLabel

Here is my current code (in a class extending JPanel):

icon = new ImageIcon(getClass().getResource("resources/icon.png"));
lblIcon.setIcon(icon);

Here is a picture of my project structure:

enter image description here

The image is in the resources directory and the screen in in the screens\jpanel.java directory

Kasper Davidsen :

If I rememeber correctly, IntelliJ automatically adds the contents of the folder marked as "resources root" to the root of your compiled project.

getClass().getResource("...") expects a path relative to your classloader, thus you simply need to provide the name of your image in this case:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31416&siteId=1