public class DisplayImage extends Panel {
BufferedImage bImg;
static int i = 0;
public ShowImage() {
try {
bImg = ImageIO.read(new File("C:/DesktopPics/pic.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawImage(bImg, 0, 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Panel panel = new DisplayImage();
frame.getContentPane().add(panel);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Okay so I got this above code, which frankly works perfectly fine, HOWEVER, my intentions were to actually put a bunch of pictures into a BufferedImage array, and draw them one by one. This works great if I create multiple BufferedImages, but when I do this:
BufferedImage[] bImg;
and later initialize it like this
bImg[0] = ImageIO.read(new File("C:/DesktopPics/pic.jpg"));
It gives me this error:
Exception in thread "main" java.lang.NullPointerException
at ShowImage.<init>(ShowImage.java:17)
at ShowImage.main(ShowImage.java:31)
I tried using ArrayList, List, even HashSet, but it won’t let me create any kind of Array/Collection for BufferedImage. Why is this? And if it’s not possible, is there another way to store a collection of images and display them without getting these errors?
Have you created your bImg array? It doesn’t appear like you’ve done so as we see only the declaration of the variable not the initialization of it.
i.e., we see this:
but not this:
Also, why are you trying to mix Swing with AWT components. This is usually not a very good idea unless you have a strong indication for doing so (I don’t see one as yet in this post) and really know what you’re doing so as to avoid the usual pitfalls.