Add image icons to buttons/labels Swing

Viewed 2412

I know that this question has already been posted, but I've tried everything I found and nothing worked.

I have a Maven project, and I want to use images on buttons. I put the images in the src/main/res folder. After a Maven clean/ Maven install, all my images are found in the target/classes folder. I want the images to be inside the .jar file, so that I don't need to create a separate folder when using it.

This is the code I try to use to load the image for a new icon on my button:

JButton button = new JButton();
      try {
        Image img = ImageIO.read(getClass().getResource("cross_icon.jpg"));
        button.setIcon(new ImageIcon(img));
      } catch (Exception ex) {
        System.out.println(ex);
      }
       subsPanel.add(button);

but I get a input == null. I tried using main/res/cross_icon.jpg or res/cross_icon.jpg, but nothing worked.

2 Answers
Related