Good day. How does positioning elements in Swing relative to layers work? How to make one element overlap another? Is there any function?

  • Do you mean pane under layers? Glass Pane, Root Pane, etc? - Mikhail Vaysman
  • Incorrectly formulated the question. I mean that all elements will be placed on one JPanel panel, and when placing, for example, one button, I need it to overlap another button. The second button will be larger than the first in size, and when hovering, I need the second button to not look out because of the first (Swing features), but still remain under the first. - TrueASL
  • Why do you need this? what problem do you solve? - Mikhail Vaysman
  • I write the game and create the main menu in it. There, in the middle, there is a panel that is hidden, and by clicking on the "Exit" button is shown (exit check, so to speak). The bottom line is that on the main panel there are more buttons in the middle, and, when an exit check appears, they overlap it, if you point it at them. - TrueASL

1 answer 1

You can use JLayeredPane. This panel allows you to add layers to any panel. Here is a running example.

public class LayeredPaneDemo extends JPanel { private LayeredPaneDemo() { setLayout(new BorderLayout()); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 310)); Point origin = new Point(10, 20); String[] layerStrings = {"Red", "Green", "Blue"}; Color[] layerColors = {Color.red, Color.green, Color.blue}; for (int i = 0; i < layerStrings.length; i++) { JLabel label = createColoredLabel(layerStrings[i], layerColors[i], origin); layeredPane.add(label, new Integer(i)); origin.x += 35; origin.y += 35; } add(layeredPane, BorderLayout.CENTER); } private JLabel createColoredLabel(String text, Color color, Point origin) { JLabel label = new JLabel(text); label.setVerticalAlignment(JLabel.TOP); label.setOpaque(true); label.setBackground(color); label.setForeground(Color.black); label.setBounds(origin.x, origin.y, 140, 140); return label; } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("LayeredPaneDemo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); JComponent newContentPane = new LayeredPaneDemo(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); }); } } 

This is a shortened version of LayeredPaneDemo . Detailed documentation of The Layered Pane .