0

I have a form with a button and an icon assigned to the button. This code was generated by NetBeans. I get an 'Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" error when trying to run the application.

I created a brand new Gradle project with an empty form and only code generated by NetBeans. I then added a button to the form. Then added an image to the project resources. Then assigned that image as an icon to the button. Clean And Build. Then Run. And then I get the NullPointerException on the code generated by NetBeans.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gradleproject1;

import javax.swing.ImageIcon;

/**
 *
 * @author x.x
 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public Main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gradleproject1/bucketHelper-icons-Chrome.png"))); // NOI18N
        jButton1.setText("jButton1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(184, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(119, 119, 119))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(86, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

And here is the stacktrace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
    at gradleproject1.Main.initComponents(Main.java:36)
    at gradleproject1.Main.<init>(Main.java:20)
    at gradleproject1.Main$1.run(Main.java:90)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Line 36 referenced in the stacktrace is...

jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gradleproject1/bucketHelper-icons-Chrome.png"))); // NOI18N

The form should display with a button and an icon in the button. This exact same process worked for an Ant project, but won't work with my new Gradle project.

gigaxr
  • 1
  • 1
  • 1
  • 2
  • I'm not sure but one time I had that error as well, on development I had to use the resource path with `"/"` but when deploying it to a JAR I had to remove that `"/"`, so, give it a try and see if it works – Frakcool May 02 '19 at 18:37

2 Answers2

2

NullPointerException happens in ImageIcon constructor in ImageIcon.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)

Your code getClass().getResource("/gradleproject1/bucketHelper-icons-Chrome.png") retruns null, then causes NullPointerException in ImageIcon

public ImageIcon (URL location) {
        this(location, location.toExternalForm());
}
0

If I had to guess,you don't need the first slash in your path.The code should be

getClass().getResource("gradleproject1/bucketHelper-icons-Chrome.png")

But to be sure,we need to see your project tree structure

laegirl
  • 144
  • 13