javaswingjframeiconsjlabel

getting null error when creating icon in JLabel


I have the following package: projectname/src/main/java/net/is/lms/project/frames In the frame folder there is a java class called testframe and an icon called icontest.png (it's 87x84px)

I have the following code snippet:

package net.is.lms.project.frames;

import javax.swing.*;

public class testframe {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(530, 600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        String url = "src/main/java/net/is/lms/project/frames/icontest.png";
        ImageIcon icon = new ImageIcon(url);

        JLabel label = new JLabel();
        label.setIcon(icon);
        frame.add(label);
    }
}

When I create the frame, no icon gets displayed

I tried different paths and also adding it like that: URL url = testframe.class.getResource("/net/is/lms/project/frames/icontest.png");


Solution

  • I don't have enough reputation to leave a comment.

    Have you tried to put the images in the src/main/resources folder and loading them like in this example: link