I have panel that is using group layout to organize some label. I want to keep this panel center of the screen when re sized. If i put the panel inside a another panel using flow layout i can keep the labels centered horizontally but not vertically. Which layout manager will allow me to keep the panel centered in the middle of the screen?
I also tried border layout and placed it in the center but it resizes to the window size.
Try using a
GridBagLayout
and adding the panel with an emptyGridBagConstrants
object.For example:
You can build you own LayoutManager to center a single component(both axis or just one). Here is the one which does it on both axis, you can easily change it to have vertical or horizontal centering.
The current implementation layouts first visible child, you can change that too...
First, I should mention, read my article on layouts: http://web.archive.org/web/20120420154931/http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/. It's old but very helpful (unfortunately that article pre-dates BoxLayout. I have some slides when I gave that talk at JavaOne, which includes BoxLayout at http://javadude.com/articles/javaone)
Try BoxLayout:
and if you want to center that stuff, use a HorizontalBox as the stuffToCenterVertically:
Way easier to "see" in the code than gridbag
GroupLayout on the panel itself, with
GroupLayout.Alignment.CENTER
, for both vertical and horizontal, andsetPreferredSize(new Dimension(yourChosenWidth,yourChosenHeight))
to set the panel to not resize.You might also do setMinimumSize and setMaximum size on the panel, just to be safe.
If you're feeling snazzy, you can just use one single GroupLayout for the whole thing, by carefully choosing parallel/sequential groups and grouping the labels appropriately.