JPanel背景图像 [英] JPanel background image

查看:111
本文介绍了JPanel背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,它确实发现了图像,所以这不是我关心的问题,我关心的是如何使该图像成为面板的背景。我试图与图形工作,但我不工作,任何想法?请问??

  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(Could not find file:+ imagen);
}

} catch ...


解决方案

这里的代码存在错误。在取消引用它之前,将 grafica 设置为 null 。这肯定会引发 NullPointerException 。您应该使用传递给将用于绘画的方法的方法,而不是声明自己的Graphics对象。要在Swing中执行此操作,您应该实现 paintComponent 方法来绘制图像,如下所示:

  public void paintComponent(Graphics grafica){
grafica.drawImage(imgFondo,0,0,this);
}

请注意,您不希望执行长时间运行的任务,如阅读绘画线程中的磁盘中的图像文件。上面的例子假定你已经加载了 imgFondo 并且存储了它,这样它就可以在 paintComponent 方法中访问。

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

这篇关于JPanel背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆