Java Swing How to - Keep preferred sizes of components in center of BorderLayout








Question

We would like to know how to keep preferred sizes of components in center of BorderLayout.

Answer

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
//ww  w  .j  a v a  2  s.co m
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  public static void main(String args[]) {
    Main bnb = new Main();
    bnb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    bnb.createUI();
    bnb.setVisible(true);
  }

  public void createUI() {
    JPanel borderPanel = new JPanel(new BorderLayout());

    JLabel northLabel = new JLabel("Nawth");
    borderPanel.add(northLabel, BorderLayout.NORTH);


    JComboBox southCombo = new JComboBox();
    borderPanel.add(southCombo, BorderLayout.SOUTH);

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
 
    JComboBox firstCombo = new JComboBox();
    centerPanel.add(firstCombo);
    centerPanel.add(Box.createVerticalGlue()); 
    JPanel centerPanelConstrain = new JPanel(new GridBagLayout());
    centerPanelConstrain.add(centerPanel);
    borderPanel.add(centerPanelConstrain, BorderLayout.CENTER);

    getContentPane().add(borderPanel);
    pack();
  }

}