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):
-
Use a
GridBagLayout
with an emptyGridBagConstraints
object, like this:parent_panel.setLayout(new GridBagLayout()); parent_panel.add(child_panel, new GridBagConstraints());
-
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());
Author by
stillStudent
Updated on June 05, 2022Comments
-
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 over 14 yearsCan you provide more of your code. Those two lines look fine, but it would be nice to see all of what you did.
-
DJClayworth over 14 yearsAre there other children of parent_panel? And are you overriding the size of childPanel?
-
stillStudent over 14 yearsI 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 over 14 yearsDo 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 over 14 years@mmyers I do not want anything at top just want that space blank.
-