Why does my icon handling code throw a NullPointerException?

后端 未结 6 2230
梦如初夏
梦如初夏 2020-12-16 07:12

I have added an image for my button,but when I run that frame this exception will be thrown .why?please help me.

init:

deps-jar:
compile-single:
run-single:         


        
相关标签:
6条回答
  • 2020-12-16 07:31

    In order to fix this, the images need to be copied in the bin directory - not in src directory.

    Otherwise you will get null all the time on getClass().getResource("image.png"). The path is not null and you can set it as the above - only if you copy the images that you need inside the binary directory, where .class files for your project are located.

    This fixed the problem. Let me know if I helped in this.

    Ioana

    0 讨论(0)
  • 2020-12-16 07:40

    This means, that getClass().getResource("/Images/yahoo_1.gif") returns null.

    JavaDoc states that this happens if

    the resource could not be found or the invoker doesn't have adequate privileges to get the resource.

    1. Check if getResource really returns null:
      System.out.println(getClass().getResource("/Images/yahoo_1.gif"));

    2. Make sure that your path is correct and that it is in your classpath.

    EDIT:

    I just tried it with NetBeans. I created the following structure

    Source Packages
      Images
        yahoo_1.gif
    

    and your code worked fine. Is this your structure?

    Try to right-click on your application and select Clean and Build.

    0 讨论(0)
  • 2020-12-16 07:46

    I had the same problem. What worked for me was:

    1. Look into the jar file or in the bin folder(the one with .class files) and see the path of image.
    2. List item
    0 讨论(0)
  • 2020-12-16 07:46
    private class HandlerClass implements ActionListener{
            public void actionperformed(ActionEvent event){
                JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
            }
    
    }
    
    0 讨论(0)
  • 2020-12-16 07:48

    The URL being passed in is null from this line:

    getClass().getResource("/Images/yahoo_1.gif")
    

    From the JDK documentation:

    [getResource(..) returns] A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource

    Maybe you meant ("Images/yahoo_1.gif") - i.e. relative path not absolute?

    0 讨论(0)
  • 2020-12-16 07:55

    It looks like getClass().getResource("/Images/yahoo_1.gif") returns null i.e. the .gif cannot be found on your classpath. (Images versus images maybe?)

    0 讨论(0)
提交回复
热议问题