views:

187

answers:

2

This is my code, it indeed finds the image so that is not my concern, my concern is how to make that image be the background of the panel. I'm trying to work with Graphics but i doesnt work, any ideas?? please??

try {
            java.net.URL imgURL = MAINWINDOW.class.getResource(imagen);

            Image imgFondo = javax.imageio.ImageIO.read(imgURL);
            if (imgFondo != null) {
                Graphics grafica=null;
                grafica.drawImage(imgFondo, 0, 0, this);
                panel.paintComponents(grafica);
            } else {
            System.err.println("Couldn't find file: " + imagen);
            }

        } catch...
+2  A: 

There is an error in your code here. You set your grafica to null the line before you dereference it. This will certainly throw a NullPointerException. Instead of declaring your own Graphics object, you should use the one passed in to the method you will be using for painting. To do this in Swing, you should implement the paintComponent method to paint your image, something like this:

  public void paintComponent(Graphics grafica) {
     grafica.drawImage(imgFondo, 0, 0, null); //no need for ImageObserver here
  }

Note that you don't want to be doing long running tasks like reading in Image files from disk in the painting thread. The above example assumes that you have already loaded the imgFondo and have it stored such that it is accessible in the paintComponent method.

akf
Thanks, so does this mean I have to override the method? or just implement it in my class?
Zloy Smiertniy
If you implement it, you will be overriding the super's method.
akf
A: 

If you are just going to draw the image at its original size then all you need to do is add the image to a JLabel and then use the label as a Container by setting its layout manager.

The only time you need to do custom painting is if you want to scale or tile the background image or do some other fancy painting.

See Background Panel for more information on both approaches.

also, check out the section from the Swing tutorial on Custom Painting.

camickr
Thanks! the links are very usefull. I have another question, I know how to put the image in the label, but how do I make that label be under all the other components? In my application I'm creating both dynamic and static components.
Zloy Smiertniy
I don't understand the question. I gave you an example of how to do this in the "Background Panel" link. I gave you 4 lines of code that shows you how to make the label behave just like a JPanel so that you can use it as the content pane of the frame. If you need more help post your SSCCE: http://sscce.org
camickr