Setting the panel in the center of the screen using the layout

I tried to set the position of the child panel in the center of the parent panel using

parent_panel.setLayout(new BorderLayout());
parent_panel.add(child_panel, BorderLayout.CENTER);

But it is added in the middle of the horizontal screen, but vertically up.

What do I need to do to add it to the center of the screen vertically and horizontally?

+3
source share
1 answer

If I understood correctly, you need an interface something like this:

+ -------- Parent panel -------- +
| |
| |
| + --- Child panel ---- + |
| | | |
| | | |
| | | |
| | | |
| + -------------------- + |
| |
| |
+ ------------------------------ +

... and you have no other components added to the parent panel.

, , ( , , , ):

  • GridBagLayout GridBagConstraints , :

    parent_panel.setLayout(new GridBagLayout());
    parent_panel.add(child_panel, new GridBagConstraints());
    
  • BoxLayout, :

    parent_panel.setLayout(new BoxLayout(parent_panel, BoxLayout.PAGE_AXIS));
    Box horizontalBox = Box.createHorizontalBox(); 
    horizontalBox.add(Box.createHorizontalGlue()); 
    horizontalBox.add(child_panel); 
    horizontalBox.add(Box.createHorizontalGlue()); 
    Box verticalBox = Box.createVerticalBox(); 
    verticalBox.add(Box.createVerticalGlue()); 
    verticalBox.add(horizontalBox); // one inside the other
    verticalBox.add(Box.createVerticalGlue()); 
    
+7

Source: https://habr.com/ru/post/1736170/


All Articles