-2

I 've this Java Code i compile with Eclipse and i 've zero error, but the console said

"Exception in thread "main" java.lang.NullPointerException"

It's an exampple from a book. I don't understand, someone know the reason?

package com.demo;

import javax.swing.JFrame;
import java.awt.Image;
import java.net.URL;
import javax.swing.ImageIcon;

public class JFrameContainer extends JFrame
{
    public JFrameContainer()
    {
        super("Una finestra");

        // scelgo l'icona da attribuire alla finestra
        URL icon_url = getClass().getResource("computer.png");
        Image icon = new ImageIcon(icon_url).getImage();
        setIconImage(icon);
    }

    public static void main(String args[])
    {
        JFrameContainer window = new JFrameContainer();
        
        // imposto le dimensioni della finestra
        window.setSize(350, 200);
        // scelgo cosa succederà quando si chiuderà la finestra
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // rendo visibile la finestra
        window.setVisible(true);
        // centro la finestra nello schermo
        window.setLocationRelativeTo(null);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sladfive
  • 17
  • 5
  • 3
    The only possible location i can see where the cause for null pointer could occur in this way is `URL icon_url = getClass().getResource("computer.png");` Try to see if it finds the icon_url and if not then you might have some path issue. – Marko Taht Apr 14 '22 at 19:44

1 Answers1

0

As this page says, it appears as though your files are in the wrong place, more specifically, the computer.png file. It also mentions that when you make it into a .jar file, it would work.

This question might help you understand where the file is actually located, and how to use it.

PlainXYZ
  • 126
  • 1
  • 8