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 empty GridBagConstrants
object.
For example:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
JPanel panel = new JPanel();
panel.add(new JLabel("This is a label"));
panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
frame.add(panel, new GridBagConstraints());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
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:
Box verticalBox = Box.createVerticalBox();
verticalBox.add(Box.createVerticalGlue());
verticalBox.add(stuffToCenterVertically);
verticalBox.add(Box.createVerticalGlue());
and if you want to center that stuff, use a HorizontalBox as the stuffToCenterVertically:
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(Box.createHorizontalGlue());
horizontalBox.add(stuffToCenter);
horizontalBox.add(Box.createHorizontalGlue());
Way easier to "see" in the code than gridbag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With