Java - 控制 JPanel 的 Z 顺序
简而言之,我的需要是在我的java应用程序中拥有一个背景图像,并在发生某些事件时,在该图像之上创建一些其他图形。
我想我会使用 JPanel 来绘制背景图像,将其添加到程序开头的 JFrame 中,然后在发生某些事件时在其之上添加其他 JPanel。问题是 Swing 给 JPanel 首先添加了最高的 Z 索引,所以我的背景应该显示在所有内容之上。
有什么方法可以控制 JPanel 的 Z 索引/顺序,还是我的做法完全错误?
In short, my need is to have a background Image in my java app, and upon some event, create some other graphics on top of that image.
I was thinking I would use a JPanel to draw the background image in, add it at to my JFrame the start of program, and then add other JPanels on top of that upon certain events. The problem is Swing gives the JPanels added first the highest Z index, so what should be my background is showing up on top of everything.
Is there any way to control the Z index/order of the JPanels, or am I going about this completely wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
setComponentZOrder()
来处理应用程序中的 Z 顺序。资源:
You can use the
setComponentZOrder()
to handle Z-Order in your application.Resources :
JLayeredPane 就是为此目的而设计的。它允许您控制组件的 Z 顺序。
The JLayeredPane is designed for just this purpose. It allows you to control the Z-order of components.
添加多个 JPanel 并使用 z 顺序听起来很奇怪。我建议您简单地添加一个 JPanel 并覆盖 PaintComponent(Graphics g) 方法,您可以根据事件绘制正确的图像。
或者使用 CardLayout,并添加 JLabels(使用不同的图像),然后当事件触发时,使用
显示正确的 JLabel。
Sounds strange to add mutiple JPanels and use z-order. I would suggest you either simple add ONE JPanel with the paintComponent(Graphics g) method overwritten, where you draw the correct image according to your events.
Or use the CardLayout, and add JLabels (with different images), then when your event triggers, use
to show the correct JLabel.
听起来很合理。
向面板添加面板就像向面板添加另一个组件一样。子组件将绘制在父面板的顶部。无需考虑 Z 顺序。
关键是在带有图像的面板上设置布局管理器。然后,添加到图像面板的每个面板都必须设为不透明,以便绘制背景图像。
也许背景面板可以帮助您。它会自动使直接添加到面板的任何组件变得不透明。
Sounds reasonable.
Adding a panel to a panel is just like adding another component to the panel. The child component will be painted on top of the parent panel. There is no need to play around with Z-Order.
The key is to set a layout manager on the panel with the image. Then each panel you add to the image panel must be made non-opaque so that the background image will be painted.
Maybe the Background Panel can help you out. It automatically makes any component added directly to the panel non-opaque.