-2

I'am a beginner and I've met some problems when I attempted to use a JPG to make a label.
and it shows that
Exception in thread "main" java.lang.NullPointerException

at javax.swing.ImageIcon.(Unknown Source)

at pane.MyImageIcon.(MyImageIcon.java:11)

at pane.MyImageIcon.main(MyImageIcon.java:21)

package pane;
import java.net.*;
import java.awt.*;
import javax.swing.*;
public class MyImageIcon extends JFrame {
public MyImageIcon() {
    JFrame jf=new JFrame();
    Container container = jf.getContentPane();
    JLabel jl = new JLabel("it is a frame", JLabel.CENTER);
    URL url = MyImageIcon.class.getResource("ofii.jpg");
    Icon icon = new ImageIcon(url); 
    jl.setIcon(icon); 
    jl.setHorizontalAlignment(SwingConstants.CENTER);
    jl.setOpaque(true);
    container.add(jl); 
    jf.setSize(800,800); 
    jf.setVisible(true); 
    jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
    new MyImageIcon(); 
}
}
  • So what statement is causing the problem? What variable at that statement is null? Once you know that you can fix the problem (or at least ask us a specific question instead of just posting a stack trace). Tell us what steps you took to debug the problem? – camickr Dec 09 '17 at 22:47
  • Based on your usage of `Class#getResource`, it will search the package `pane` for the image named `ofii.jpg`. Make sure the image exists in the correct location. You can use `/ofii.jpg` to reference a image at the top of the class-path or a relative path if you know the relationship between the package and the location of the image. This all assumes that the image is contained within the class-path context – MadProgrammer Dec 09 '17 at 22:51

2 Answers2

0

Print out variable "url". You will find it being null. Check if the image actually exists in the jar, on the given path. These posts might help:

SurfMan
  • 1,685
  • 12
  • 19
0

Unknown source usually means it can't find the image, Make sure the image exists and is placed in the same location as your Java class file, if not, you can use classpath relative paths in getResource() putting / at the start

A.A
  • 743
  • 1
  • 8
  • 20