The image path is all correct only, I don’t know why this error is coming.
Any one have any idea?
Code is for putting a background image in a frame and add button over that image
The error is
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:99)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:113)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:240)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:172)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:136)
Code
Error is coming while running the code :
public class BackgroundImg extends JPanel {
private Image img;
public BackgroundImg (String img)
{
this(new ImageIcon(img).getImage());
}
public BackgroundImg (Image img)
{
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
//setLayout(null);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
}
public class ApplicationFrame {
public static void main(String[] args) throws ImageAccessException {
BackgroundImg panel = new BackgroundImg(Toolkit.getDefaultToolkit().createImage(ApplicationFrame.class.getResource("C:\\test.png")));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.getContentPane().add(panel);
ApplicationContents.addContentsToPane(panel);
frame.setVisible(true);
// frame.setVisible(true);
}
}
}
public class ApplicationContents {
public static void addContentsToPane(Container pane)
{
//pane.setLayout(null);
pane.setLayout(new FlowLayout());
JButton b1 = new JButton("Test");
pane.add(b1);
//Insets insets = pane.getInsets();
//Dimension size = new Dimension(120,32);
// b1.setBounds(0 + insets.left, 0 + insets.top,
// size.width, size.height);
b1.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(null, "Test" , "Test", JOptionPane.ERROR_MESSAGE);
}
}
);
}
}
getResource() loads a resource from classpath, not an OS path, so even if “C:\test.png” would be correct you cannot load it that way.
Also, please check the return value of getResource() before using it so you’d catch these kinds of errors.
You might want to bundle the image as a resource within your jar and load it using path that specifies the location within your jar.