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("Couldn't find file: " + imagen);
}
} catch...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码此处有错误。您可以在取消引用该行之前将其
grafica
设置为null
。这肯定会抛出NullPointerException
。您不应声明自己的 Graphics 对象,而应使用传递给将用于绘画的方法的对象。要在 Swing 中执行此操作,您应该实现paintComponent
方法来绘制图像,如下所示:请注意,您不希望执行长时间运行的任务,例如从磁盘中读取图像文件绘画线。上面的示例假设您已经加载了
imgFondo
并将其存储起来,以便可以在paintComponent
方法中访问它。There is an error in your code here. You set your
grafica
tonull
the 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 thepaintComponent
method 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
imgFondo
and have it stored such that it is accessible in thepaintComponent
method.如果您只想以其原始大小绘制图像,那么您所需要做的就是将图像添加到 JLabel,然后通过设置其布局管理器将该标签用作容器。
您需要进行自定义绘画的唯一时间是如果您想要缩放或平铺背景图像或进行其他一些精美的绘画。
有关这两种方法的更多信息,请参阅后台面板。
另外,请查看 Swing 教程中有关 自定义绘画。
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.