I am trying to run this code (Ignore the paimon bit):

    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;

    public class optionpanes {

        public static void main(String Args[]){
            ImageIcon icon = new ImageIcon(optionpanes.class.getResource("Paimon_1.png"));
            JOptionPane.showOptionDialog(null, "Can I have that?", "Hungry Paimon", 
            JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, icon, null, 0);
        }
    }

but I only get: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null at java.desktop/javax.swing.ImageIcon.(ImageIcon.java:217) at optionpanes.main(optionpanes.java:23)

My project is D:\Java\GUI\Optionpanes

Is there a different more reliable way to get the image because I've been seeing .getResource a lot but it really isn't helping me

1

There are 1 best solutions below

0
Renis1235 On

There are several ways to read the content of a file in Java. What your code tries to do, is find the file in a specific folder called the resources folder. It is a specified folder where the, well... Resources are. And that is exactly what you have there.

A static image should be part of this folder. If you are using an IDE, just put the image in the resources folder and try to read it the same way.

If you want to read it in a specific place in the drive (not recommended since when you create a .jar file, or delete the image file, it will not be accessible).

Use this way:

ImageIcon icon = new ImageIcon("D:\\Java\\GUI\\Optionpanes\\Paimon_1.png");