简体   繁体   中英

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");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM