Draw BufferedImage to panel

I’m a complete noob to Java 2d but perhaps you can help me out. I’m trying to test drawing an image to a panel. My does nothing. I’ve tested this same method with drawstring and it works fine.

@Override
        public void paintComponent(Graphics g) {

             BufferedImage temp = null;
        try {
                temp = ImageIO.read(new File("/res/image/girls.JPG"));
            } catch (IOException e) 
                   
               {
                   //catch exception
               }
            super.paintComponent(g);
            g.drawImage(temp, 0, 0, ViewPort.this);
        }

Works fine when I use graphics to draw text and shapes. I double checked my image location. Any help would be nice.

My first thought would be to have [icode]e.printStackTrace();[/icode] in your catch clause just in case some error is being thrown there.

As per the documentation, [icode]drawImage()[/icode] does nothing if the image is null, which would happen if there were an error and the image wasn’t loaded.

http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage(java.awt.Image,%20int,%20int,%20java.awt.image.ImageObserver)

Thanks , apparently it can’t read the input file.

When you load a file using IO the file path starts where the application launches correct ?

As far as I am aware. Maybe take out the leading / in your file location?

Also, you probably don’t want to be loading the image in every call to paintComponent()! :wink: To start with, make the image a field and load it once (eg. in the constructor).

I found the .class file in my build folder with is two directories down from the res folder. I added …/…/ but it still doesn’t be able to seem to find the file. I’m about to use a file picker and see if that helps. At least then I will know it is the path and not some other problem. But until then lunch time ;D

Where is “res” in the project? if it is the src folder you must have “src” before “/res”