java JPanel 背景图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2937403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:32:35  来源:igfitidea点击:

JPanel background image

javaimagegraphicsjpanel

提问by lesolorzanov

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??

这是我的代码,它确实找到了图像,所以这不是我关心的,我关心的是如何使该图像成为面板的背景。我正在尝试使用 Graphics,但我不起作用,有什么想法吗??请??

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...

采纳答案by akf

There is an error in your code here. You set your graficato nullthe 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 paintComponentmethod to paint your image, something like this:

您的代码中存在错误。在取消引用之前,您graficanull其设置为该行。这肯定会抛出一个NullPointerException. 与其声明您自己的 Graphics 对象,不如使用传递给您将用于绘画的方法的对象。要在 Swing 中执行此操作,您应该实现paintComponent绘制图像的方法,如下所示:

  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 imgFondoand have it stored such that it is accessible in the paintComponentmethod.

请注意,您不想执行长时间运行的任务,例如在绘画线程中从磁盘读取图像文件。上面的示例假设您已经加载imgFondo并存储了它,以便在paintComponent方法中可以访问它。

回答by camickr

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.

如果您只想以原始大小绘制图像,那么您需要做的就是将图像添加到 JLabel,然后通过设置其布局管理器将标签用作容器。

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 Panelfor more information on both approaches.

有关这两种方法的更多信息,请参阅背景面板

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

另外,请查看 Swing 教程中关于自定义绘画的部分