0

I have been trying to create a resizable image by drawing BufferedImage on a panel and redrawing it whenever componentResized happened. However, despite the image loading fine in earlier versions (which either didn't resize at all or didn't do it properly) now Java claims the image isn't there. The code is as follows

    public class Image extends JPanel{
    BufferedImage img=null;

    public Image{
    try {
        img = ImageIO.read(new File("Untitled.png"));
    }
    catch (IOException e) {
    }
    Dimension d=getSize();
    Graphics g=getGraphics();
    g.drawImage(img, 0, 0, d.width, d.height, null);

even without the component listener, it returns NullPointerException on drawImage. But I know the image isn't null, since it worked previously, which leads me to thinking there's something wrong with the code here

Sparks
  • 45
  • 1
  • 1
  • 4
  • 2
    Try `System.out.println(new File("Untitled.png").getAbsolutePath());` and check if the file really is there. My guess: it isn't. – Tom Apr 14 '16 at 20:51
  • 1
    You shouldn't just dump an IOException, at least print the stack-trace, so users no, why it doesn't work for them. – Bálint Apr 14 '16 at 21:00
  • `catch (IOException e) {}` Never do this. Your `ImageIO.read` is probably throwing an exception which you don't know about because of the empty catch block. Also, you shouldn't use `getGraphics` for painting. See http://stackoverflow.com/a/15991175/2891664. – Radiodef Apr 14 '16 at 21:02
  • @Radiodef `@Override` `public void paintComponent(Graphics g) {` `super.paintComponent(g);` `g.drawImage(img, 0, 0, d.width, d.height, null);}` Should that be okay then when added to my class? Because it still shows nothing, regardless of the dimensions I give it. drawRect works fine, it just still doesn't work with the image, even though per Tom's advice I made sure that the image is there. – Sparks Apr 15 '16 at 06:11

2 Answers2

0

If something goes wrong in here: img = ImageIO.read(new File("Untitled.png")); Then you are drawing on a null reference object here:

g.drawImage(img, 0, 0, d.width, d.height, null);

That is the reason of the NPE

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

This is due to that the Graphics object g may be null. Graphics g = getGraphics();

Farag Zakaria
  • 178
  • 1
  • 9