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...
There is an error in your code here. You set your
graficatonullthe line before you dereference it. This will certainly throw aNullPointerException. 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 thepaintComponentmethod to paint your image, something like this: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
imgFondoand have it stored such that it is accessible in thepaintComponentmethod.