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?
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.
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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With