Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java layout manager vertical center

Tags:

java

layout

swing

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.

like image 223
Hamza Yerlikaya Avatar asked May 22 '09 13:05

Hamza Yerlikaya


2 Answers

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);
}
like image 96
Michael Myers Avatar answered Nov 20 '22 11:11

Michael Myers


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

like image 11
Scott Stanchfield Avatar answered Nov 20 '22 10:11

Scott Stanchfield