Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - control Z order of JPanels

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?

like image 765
tybro0103 Avatar asked Sep 21 '10 18:09

tybro0103


People also ask

What is jpanel in Java Swing?

JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.

How to add multiple jpanels in Z-order?

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

How to add components to a jpanel?

In order to add components such as button, JLabel, JTextfield, etc. we will use add () method. Since there are different versions for add (), which method is used depends on the panel’s layout manager. 1. Add (Component cmp) method will be used for layout managers such as GridLayout, FlowLayout , SpringLayout, BoxLayout. jp is the object of JPanel.

How to set the layout of a jpanel in Java?

In order to set the layout, use the method setLayout (LayoutManager lm). JPanel jp=new JPanel (new GridBagLayout); Here, a GridBagLayout is set as the layout. If we are using the syntax as. JPanel jp=new JPanel (); Then the layout is set as FlowLayout in default.


2 Answers

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


Resources :

  • JavaDoc - Container.setComponentZOrder
  • oracle.com - Mixing heavy and light components
like image 133
Colin Hebert Avatar answered Sep 19 '22 10:09

Colin Hebert


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.

like image 27
Avall Avatar answered Sep 21 '22 10:09

Avall