Setting panel at center of screen by using layout

11,857

If I understand correctly, you want an interface something like this:

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

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

If this is the case, you have two choices that I know of (based on this question, which I apparently answered):

  1. Use a GridBagLayout with an empty GridBagConstraints object, like this:

    parent_panel.setLayout(new GridBagLayout());
    parent_panel.add(child_panel, new GridBagConstraints());
    
  2. Use a BoxLayout, like this:

    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()); 
    
Share:
11,857
stillStudent
Author by

stillStudent

Updated on June 05, 2022

Comments

  • stillStudent
    stillStudent about 2 years

    I tried setting the position of child-panel at the center of parent-panel by using

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

    But it's getting added at the middle of horizontal screen but vertically at top.

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

    • JasCav
      JasCav over 14 years
      Can you provide more of your code. Those two lines look fine, but it would be nice to see all of what you did.
    • DJClayworth
      DJClayworth over 14 years
      Are there other children of parent_panel? And are you overriding the size of childPanel?
    • stillStudent
      stillStudent over 14 years
      I am not adding any other child-panel to main-panel, but I am adding other panels to above mentioned child-panel. And about code, I think these are only two lines related to the layout positioning of child-panel in main-panel.
    • palantus
      palantus over 14 years
      Do you want there to be padding at the top? If you have a border layout and you set something to be CENTER, that just means that it will fill all space that isn't occupied by something NORTH, SOUTH, EAST, or WEST.
    • stillStudent
      stillStudent over 14 years
      @mmyers I do not want anything at top just want that space blank.