Java - control Z order of JPanels

23,581

Solution 1

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


Resources :

Solution 2

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.

Solution 3

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

Solution 4

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.

Share:
23,581
tybro0103
Author by

tybro0103

Coffee junkie, computer nerd, fitness monster, and father of two cool dudes.

Updated on April 30, 2020

Comments

  • tybro0103
    tybro0103 almost 4 years

    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?