Java - control Z order of JPanels

寵の児 提交于 2019-11-29 13:45:49
Colin Hebert

You can use the setComponentZOrder() to handle Z-Order in your application.


Resources :

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

CardLayout cl = (CardLayout)getLayout();
cl.show(this, "card3");

to show the correct JLabel.

The JLayeredPane is designed for just this purpose. It allows you to control the Z-order of components.

I was thinking I would use a JPanel to draw the background image in, add it at to my JFrame the start of program,

Sounds reasonable.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!