Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

java - JPanel background image

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...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, 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 imgFondo and have it stored such that it is accessible in the paintComponent method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...