0

Have an following error code when run the code Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null

Hello everyone, I am still a student and new in Java Programming

I want to insert an image for background in JFrame using Apache Netbeans. I've tried following some tutorials on internet using labels and when I try to run them I get output like this:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
    at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:234)
    at com.project.regbengkel.MainFrame.initComponents(MainFrame.java:33)
    at com.project.regbengkel.MainFrame.<init>(MainFrame.java:17)
    at com.project.regbengkel.MainFrame$1.run(MainFrame.java:85)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:318)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:771)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:741)
    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)

The code can run perfectly but the Frame can't created, only say that "build successful" Here is my code: `/*

  • Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
  • Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package com.project.regbengkel;

public class MainFrame extends javax.swing.JFrame {

/**
 * Creates new form MainFrame
 */
public MainFrame() {
    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() {

    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/project/regbengkel/logo.png"))); // NOI18N

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(32, 32, 32)
            .addComponent(jLabel1)
            .addContainerGap(50, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(28, 28, 28)
            .addComponent(jLabel1)
            .addContainerGap(28, 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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

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

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
// End of variables declaration                   

} `

And this is list of files in my projectList of files

Can someone mention what's wrong on my code? Any help will be appreciated :)

  • Your project structure will be different when you compile the .java code into .class files. Create a resource folder at the project level and put your images and text files in the resource folder. The answers to this [Stack Overflow question](https://stackoverflow.com/questions/29580664/java-how-to-add-an-image-to-resource) will show you how. – Gilbert Le Blanc Dec 05 '22 at 08:49

1 Answers1

0

If you image is on the classpath, you don't need to prefix it with the folder structure.

It sees that you image is located in the same package as you class and is thus on the classpath.

You just need to give the image name instead.

Replace this:

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/project/regbengkel/logo.png")));

By this:

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("logo.png")));