图像和面板
我在 Image
上添加 JPanel
时遇到问题。这就是我想要做的:
Image bgImage = loadImage(filename);
JPanel jp = new JPanel();
jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);
bgImage.add(jp);
完成此操作后,我只看到 bgImage
。我尝试了一切,但仍然无法显示面板。有人可以帮助我吗?
I'm having a problem adding a JPanel
on top of an Image
. This is what I'm trying to do:
Image bgImage = loadImage(filename);
JPanel jp = new JPanel();
jp.setBounds(100,100,100,100);
jp.setOpaque(true);
jp.setBackgroudColor(Color.red);
bgImage.add(jp);
After doing this, I only see the bgImage
. I tried everything but I still can't show the panel. Can somebody help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将组件放置在
Image
内。您想要做的是将Image
绘制到 swing 组件(如JPanel
)的背景上。所有 swing 组件都有一个paint()
方法,该方法调用这三个方法(可能不完全是这个顺序):paintComponent()
、paintChildren()
,paintBorder()
。因此,您想要重写paintComponent()
方法以在面板上绘制背景图像。运行时,将调用您的自定义方法,然后调用paintChildren()
方法,该方法将在背景图像的顶部绘制所有“子”组件:You cannot place a component inside an
Image
. What you want to do is paint theImage
onto the background of a swing component (likeJPanel
). All swing components have apaint()
method that calls these three methods (perhaps not quite this order):paintComponent()
,paintChildren()
,paintBorder()
. So, you want to override thepaintComponent()
method to paint your background image over the panel. When this runs, your custom method will be called, and then thepaintChildren()
method will be called, which will paint all "child" components over the top of your background image:“BackgroundImagePanel”解决方案按实际大小绘制图像。如果这是一个要求,那么您可以只使用 JLabel 而不是创建自定义组件。
BackgroundPanel 条目显示了如何执行此操作。它还提供了一个带有更多自定义图像绘制解决方案的背景面板,如果这是您要求的一部分,您可以缩放和平铺图像。
The "BackgroundImagePanel" solution paints the image at its actual size. If this is a requirement, then you can just use a JLabel instead of creating a custom component.
The BackgroundPanel entry shows how you can do this. It also provides a background panel with more custom image painting solutions, that will allow you to scale and tile the image, if this is part of your requirement.