1

Sorry newbie here. I get an error in Netbeans while trying to add an Icon to a J label. The error is:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null

After importing all of the images I used for my project. I still get this error.

This is the code in default in Netbeans:

diceButton = new javax.swing.JButton();

diceButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/dice.png"))); // NOI18N

(https://i.stack.imgur.com/VCANk.png)

I'm expecting to add it to a jlabel so that the image will also be at the jar file

Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
Darivs E
  • 19
  • 2
  • looks like incorrect resource lookup (_resources_ is not a package, I assume?) - make sure to read and understand the api doc of getResource (and/or study https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other - same for any lookup, even though that particular QA is focused on javafx) – kleopatra Jan 18 '23 at 14:29

1 Answers1

-1

You should also try this method to better understand label and button's icon (image) property.

  • Using absolute path, like my image in D drive in img folder,

     ImageIcon icon = new ImageIcon("D:\\img\\img-name.jpg");
     img_label.setIcon(icon);
    

Or you can also do this from label/image icon- property by specifying absolute path.

axel
  • 11
  • 2
  • no - don't load resources using file api (except when actually having a file f.i. from a filechooser), it will break on deploy – kleopatra Jan 22 '23 at 16:24
  • But, I think this is the right way for beginner practice, and anyone understand better. – axel Jan 22 '23 at 16:47
  • 1
    no, particularly beginners confuse file vs. path lookup .. and the question clearly is about the latter (as I understand it) – kleopatra Jan 22 '23 at 18:16